html:canvas画布绘图简单入门-绘制时钟-3
生活随笔
收集整理的這篇文章主要介紹了
html:canvas画布绘图简单入门-绘制时钟-3
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
canvas示例系列:
- html:canvas畫布繪圖簡單入門-1
- html:canvas畫布繪圖簡單入門-2
- html:canvas畫布繪圖簡單入門-繪制時鐘-3
- html:canvas畫布繪圖簡單入門-刮刮樂-4
示例10:繪制時鐘
<canvas id="canvas"width="600"height="600"></canvas><script>let canvas = document.querySelector('#canvas');let ctx = canvas.getContext('2d');let width = canvas.widthlet height = canvas.height// 繪制內(nèi)容區(qū)域相對畫布的大小 80%let scale = 0.8;// 計算半徑let radius = Math.floor(Math.min(width, height) * scale * 0.5);console.log('radius', radius);// 繪制外邊框// ctx.beginPath();// ctx.strokeRect(0, 0, width, height);// ctx.closePath()// 繪制時鐘刻度function drawClockScale({number = 12,strokeStyle = 'black',lineWidth = 3,lineLength = 20,}) {ctx.save();ctx.strokeStyle = strokeStyle;ctx.lineWidth = lineWidth;let rotateAngle = (360 / number);for (let i = 0; i < number; i++) {ctx.rotate((Math.PI / 180) * rotateAngle);ctx.beginPath();ctx.moveTo(radius - lineLength, 0);ctx.lineTo(radius, 0);ctx.stroke();ctx.closePath()}ctx.restore();}function drawClock() {ctx.clearRect(0, 0, width, height);ctx.save();// 將坐標軸原點移動到畫布中心ctx.translate(width / 2, height / 2);// 旋轉(zhuǎn)坐標軸x指向畫布正上方ctx.rotate(-Math.PI / 180 * 90);// 分針和秒針的刻度drawClockScale({number: 60,strokeStyle: 'green',lineWidth: 4,lineLength: 14});// 時針刻度drawClockScale({number: 12,strokeStyle: 'red',lineWidth: 8,lineLength: 20});// 繪制指針let now = new Date();let hour = now.getHours();let minute = now.getMinutes();let second = now.getSeconds();console.log(`${hour}: ${minute}: ${second}`);// 繪制秒針ctx.save();ctx.beginPath();ctx.rotate((Math.PI / 180) * (360 / 60) * second);ctx.strokeStyle = "deepskyblue";ctx.lineWidth = 2;ctx.moveTo(-20, 0);ctx.lineTo(radius - 30, 0);ctx.stroke();ctx.closePath()ctx.restore();// 繪制分針ctx.save();ctx.rotate((Math.PI / 180) * ((360 / 60) * minute + (360 / 60 / 60) * second));ctx.beginPath();ctx.strokeStyle = "green";ctx.lineWidth = 4;ctx.moveTo(-20, 0);ctx.lineTo(radius - 40, 0);ctx.stroke();ctx.closePath()ctx.restore();// 處理成12小時制if (hour > 12) {hour = hour - 12}// 繪制時針ctx.save();ctx.beginPath();ctx.rotate((Math.PI / 180) * ((360 / 12) * hour + (360 / 12 / 60) * minute + (360 / 12 / 60 / 60) *second));ctx.strokeStyle = "red";ctx.lineWidth = 8;ctx.moveTo(-20, 0);ctx.lineTo(radius - 50, 0);ctx.stroke();ctx.closePath()ctx.restore();// 繪制圓心ctx.beginPath();ctx.fillStyle = "grey";ctx.lineWidth = 10;ctx.arc(0, 0, 10, 0, Math.PI / 180 * 360);ctx.fill();ctx.closePath()// 繪制圓ctx.beginPath();ctx.strokeStyle = "grey";ctx.lineWidth = 10;ctx.arc(0, 0, radius, 0, Math.PI / 180 * 360);ctx.stroke();ctx.closePath()ctx.restore();}// 每隔1秒重繪一次setInterval(() => {drawClock();}, 1000)</script>需要修改坐標軸之前,最好把當前狀態(tài)保存,繪制完成后再恢復
在線demo: https://mouday.github.io/front-end-demo/canvas/canvas-clock.html
總結(jié)
以上是生活随笔為你收集整理的html:canvas画布绘图简单入门-绘制时钟-3的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 高校俱乐部发福利啦,晚了就没了,速度~
- 下一篇: 量测水监测站