demo地址:

https://lyf521.github.io/docs/blog/animation/drawClock.html

一、canvas常用方法

  1. var canvas = document.getElementById('canvas')
  2. var ctx = canvas.getContext('2d')
  3. // 移动端画图模糊处理 **注意canvas画布宽和style width的区别
  4. canvas.width *= 2
  5. canvas.height *= 2
  6. ctx.scale(2, 2)
  7. ctx.clearRect(0, 0, canvas.width, canvas.height) // 清除画布
  8. ctx.save() // 保存画布设置的样式
  9. cxt.beginPath() // 开始 路径
  10. ctx.lineWidth = 7 //设置画线宽
  11. ctx.strokestyle = '#f00' // 设置画笔颜色
  12. // 画圆,坐标[250,250], 半径200, 整圆(0-360) Math.PI = 180 false顺时针
  13. ctx.arc(250,250,200,0,Math.PI*2,false)
  14. ctx.stroke() // 画图
  15. ctx.closePath() // 结束路径
  16. // 绕圆圈画线段 -- 时钟刻度
  17. for(var i = 0; i < 12; i++) {
  18. cxt.save() // 保存样式
  19. cxt.lineWidth = 7
  20. cxt.strokeStyle = '#000'
  21. cxt.translate(250, 250) // 设置异次元空间的原点(250,250)相当于变为(0,0)
  22. cxt.rotate(i*30*Math.PI/180) // 设置旋转角度30deg
  23. cxt.beginPath() //画笔开始
  24. cxt.moveTo(0, -170) // 画线,从坐标0,-170开始
  25. cxt.lineTo(0,-190) // 到坐标0,-190结束
  26. cxt.stroke() // 画图
  27. cxt.closePath()
  28. cxt.restore() //返回之前保存过的路径状态和属性
  29. }
  30. // 画文字
  31. ctx.font = 'bold 28px Sans-Serif'
  32. ctx.textAlign = 'center'
  33. ctx.textBaseline = 'middle'
  34. ctx.fillText('nihao', 250, 250)

二、坐标点旋转向量计算方式

  1. // 在canvas xy坐标系中, 某坐标饶某点旋转后的 坐标
  2. class CountNexPos{
  3. constructor (center = [250,250]){
  4. this.center = center
  5. }
  6. NexPos(curPos,theta){ // curPos:[x1,y1], theta: 角度值
  7. theta = theta / 180 * Math.PI // 角度值转换为 旋转的度数
  8. var nexPos = []
  9. nexPos[0] = (curPos[0] - this.center[0])*Math.cos(theta) - (curPos[1] - this.center[1]) * Math.sin(theta) + this.center[0]
  10. nexPos[1] = (curPos[0] - this.center[0])*Math.sin(theta) + (curPos[1] - this.center[1]) * Math.cos(theta) + this.center[1]
  11. return nexPos
  12. }
  13. }