demo地址:
https://lyf521.github.io/docs/blog/animation/drawClock.html
一、canvas常用方法
var canvas = document.getElementById('canvas')var ctx = canvas.getContext('2d')// 移动端画图模糊处理 **注意canvas画布宽和style width的区别canvas.width *= 2canvas.height *= 2ctx.scale(2, 2)ctx.clearRect(0, 0, canvas.width, canvas.height) // 清除画布ctx.save() // 保存画布设置的样式cxt.beginPath() // 开始 路径ctx.lineWidth = 7 //设置画线宽ctx.strokestyle = '#f00' // 设置画笔颜色// 画圆,坐标[250,250], 半径200, 整圆(0-360) Math.PI = 180 false顺时针ctx.arc(250,250,200,0,Math.PI*2,false)ctx.stroke() // 画图ctx.closePath() // 结束路径// 绕圆圈画线段 -- 时钟刻度for(var i = 0; i < 12; i++) {cxt.save() // 保存样式cxt.lineWidth = 7cxt.strokeStyle = '#000'cxt.translate(250, 250) // 设置异次元空间的原点(250,250)相当于变为(0,0)cxt.rotate(i*30*Math.PI/180) // 设置旋转角度30degcxt.beginPath() //画笔开始cxt.moveTo(0, -170) // 画线,从坐标0,-170开始cxt.lineTo(0,-190) // 到坐标0,-190结束cxt.stroke() // 画图cxt.closePath()cxt.restore() //返回之前保存过的路径状态和属性}// 画文字ctx.font = 'bold 28px Sans-Serif'ctx.textAlign = 'center'ctx.textBaseline = 'middle'ctx.fillText('nihao', 250, 250)
二、坐标点旋转向量计算方式
// 在canvas xy坐标系中, 某坐标饶某点旋转后的 坐标class CountNexPos{constructor (center = [250,250]){this.center = center}NexPos(curPos,theta){ // curPos:[x1,y1], theta: 角度值theta = theta / 180 * Math.PI // 角度值转换为 旋转的度数var nexPos = []nexPos[0] = (curPos[0] - this.center[0])*Math.cos(theta) - (curPos[1] - this.center[1]) * Math.sin(theta) + this.center[0]nexPos[1] = (curPos[0] - this.center[0])*Math.sin(theta) + (curPos[1] - this.center[1]) * Math.cos(theta) + this.center[1]return nexPos}}
