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 *= 2
canvas.height *= 2
ctx.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 = 7
cxt.strokeStyle = '#000'
cxt.translate(250, 250) // 设置异次元空间的原点(250,250)相当于变为(0,0)
cxt.rotate(i*30*Math.PI/180) // 设置旋转角度30deg
cxt.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
}
}