介绍最早由Apple引入WebKit用于MacOSX的Dashboard,然后被各种浏览器实现。今天,所有主流浏览器都支持它。CanvasAPI提供了一种通过JavaScript和HTML的元素绘制图形的方法。它可用于动画、游戏画面、数据可视化、图像编辑和实时视频处理。Canvas适用于绘制具有大数据量图形元素的图表(如地理坐标系或平行坐标系上的热图、大比例折线图或散点图等),也适用于实现一定的视觉效果。它还能够以png、jpg或webp格式保存图像。Canvas提供了强大的Web绘图能力,所以我们要学会使用它。效果:创建画布默认情况下,元素没有边框,也没有内容。默认尺寸为300px×150px(宽×高),我们可以使用width和height属性指定。获取Canvas和Radius为了在上绘制图形,我们需要使用一个JavaScript上下文对象,它可以动态创建图像。这里建立了一个CanvasRenderingContext2D二维渲染上下文。constctx=canvas.getContext('2d');letradius=canvas.height/2;绘制圆圈和时钟中心beginPath()用于开始路径,或重置当前路径。arc()用于创建圆或弧。fill()用于填充图形。stroke()用于绘制路径。functiondrawFace(context,radius){context.beginPath();context.arc(0,0,radius,0,2*Math.PI);context.fillStyle='white';context.fill();//重设置绘制时钟中心点的路径context.beginPath();context.arc(0,0,radius*0.06,0,2*Math.PI);context.fillStyle='green';context.fill();}draw拨号rotate()用于旋转当前绘图。360度等于Math.PI*2,Math.PI/6是30度。translate()用于将原点移动到新位置。fillText()用于绘制文本。函数drawNumbers(context,radius){context.fillStyle='green';context.font=radius*0.15+'pxarial';context.textBaseline='middle';context.textAlign='center';for(letnum=1;num<=12;num++){constangle=num*Math.PI/6;context.rotate(angle);context.translate(0,-radius*0.82);context.rotate(-angle);context.fillText(num.toString(),0,0);context.rotate(angle);context.translate(0,radius*0.82);context.rotate(-angle);}}绘制表盘刻度moveTo()移动路径到指定点。lineTo()添加一个新点并创建一条从最后指定的点到该点的直线。functiondrawLine(context,radius){context.lineCap='butt';for(leti=1;i<=60;i++){context.strokeStyle=i%5===0?'yellowgreen':'lightgray';context.beginPath();context.lineWidth=i%5===0?半径*0.03:半径*0.02;context.rotate(i*Math.PI/30);context.moveTo(0,-radius);context.lineTo(0,i%5===0?-radius*0.93:-radius*0.96);context.stroke();context.rotate(-i*Math.PI/30);}}绘图显示盘时、分、秒针functiondrawTime(context,radius){constdate=newDate();consth=date.getHours();constm=date.getMinutes();consts=date.getSeconds();consthourAngle=(h*Math.PI/6)+(m*Math.PI/(6*60))+(s*Math.PI/(6*60*60));constminuteAngle=(m*Math.PI/30)+(s*Math.PI/(30*60));constsecondAngle=(s*Math.PI/30);drawHand(context,hourAngle,radius*0.5,radius*0.05,'green');drawHand(context,minuteAngle,radius*0.7,radius*0.04,'dodgerblue');drawHand(上下文,secondAngle,半径*0.9,radius*0.02,'orange');}functiondrawHand(context,angle,length,width,color){context.beginPath();context.lineWidth=width;context.lineCap='round';//圆端context.moveTo(0,0);context.rotate(angle);context.lineTo(0,-length);context.strokeStyle=color;context.stroke();context.rotate(-angle);}addstyle由于canvas会有锯齿状的圆圈,这里的CSS样式会比较圆canvas{background:green;border-radius:50%;}启动时钟translate(radius,radius)将位置移动到画布的中心。ctx.translate(radius,radius);radius=radius*0.9;//时钟半径函数
使用CanvasAPI模拟彩色时钟相关文章