本文主要是介绍canvas画图-钟表,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
调用了window.requestAnimationFrame(绘制函数),然后在绘制函数中继续调用 window.requestAnimationFrame(绘制函数),这种情况下,每一次绘制都不能影响下一次,故需要在变换开始和结束的时候添加 ctx.save()/ctx.restore()
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title></title><link rel="stylesheet" href="">
</head>
<body><canvas width="200" height="200" style="border: 1px solid #000"></canvas><script>const ctx = document.querySelector('canvas').getContext('2d')function draw() {let time = new Date()let h = time.getHours()h = h>12?h-12:hlet m = time.getMinutes()let s = time.getSeconds()ctx.save()ctx.clearRect(0, 0, 200, 200)ctx.scale(0.5, 0.5)ctx.translate(200, 200)// 绘制直线等都是水平绘制的,反向旋转90度,正好同时间统一起来ctx.rotate(-Math.PI/2)// set gloabal ctx stylesctx.fillStyle = '#fff'ctx.strokeStyle = '#000'ctx.lineWidth = 8ctx.lineCap = 'round'// draw hour marks,12个刻度,每隔2*Math.PI/12ctx.save()for(let i=0;i<12;i++){ctx.beginPath()ctx.moveTo(160,0)ctx.lineTo(175,0)ctx.stroke()ctx.rotate(Math.PI/6)}ctx.restore()// draw minute marks,一共60个刻度,碰到5的倍数就省略不画,每隔2*Math.PI/(12*5)ctx.save()ctx.lineWidth = 5for (let i = 0; i < 60; i++) {if(i%5!==0){ctx.beginPath()ctx.moveTo(164, 0)ctx.lineTo(170, 0)ctx.stroke()}ctx.rotate(Math.PI / 30)}ctx.restore()// NUMBERctx.save()ctx.fillStyle = "#000"ctx.font = "30px verdana"ctx.rotate(Math.PI / 2)for (let i = 1; i <= 12; i++) {// 半径为圆盘的半径 - 20let x = 140 * Math.sin(i * Math.PI / 6)let y = -140 * Math.cos(i * Math.PI / 6)ctx.fillText(i, x - 10, y + 9)}ctx.restore()//draw hourctx.save()ctx.lineWidth = 12ctx.rotate(h*Math.PI/6+m*Math.PI/360+s*Math.PI/21600)ctx.beginPath()ctx.moveTo(-15,0)ctx.lineTo(105,0)ctx.stroke()ctx.restore()//draw minutectx.save()ctx.lineWidth = 6ctx.rotate( m *2* Math.PI / 60 + s *2* Math.PI / (60*60))ctx.beginPath()ctx.moveTo(-20, 0)ctx.lineTo(126, 0)ctx.stroke()ctx.restore()// draw seconds ctx.save()ctx.lineWidth = 3ctx.rotate(s*Math.PI/30)ctx.strokeStyle = "#f00"ctx.beginPath()ctx.moveTo(-25,0)ctx.lineTo(110,0)ctx.stroke()ctx.beginPath()ctx.fillStyle = "red"ctx.arc(0, 0, 10,0, 2 * Math.PI, true)ctx.fill()ctx.beginPath()ctx.arc(120,0, 10, 0, 2*Math.PI, true)ctx.stroke()ctx.restore()// drwa clock circlectx.save()ctx.strokeStyle = "#325fa2"ctx.beginPath()ctx.arc(0,0, 180, 0, 2*Math.PI, true)ctx.stroke()ctx.restore()ctx.restore()window.requestAnimationFrame(draw)}window.requestAnimationFrame(draw)</script>
</body>
</html>
这篇关于canvas画图-钟表的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!