javascript - 如何在值后更新画布?
问题描述
我正在尝试使用香草 javascript 实现时钟。
问题是画布在超过 60 秒后没有更新。每 60 秒后,它应该以一个空圆圈开始。
而且,当我应用用于将秒数映射到角度的相同逻辑时,数分钟内都无法正常工作。
这是我尝试过的
var c = document.getElementById("myCanvas");
c.width = window.innerWidth;
c.height = window.innerHeight;
var ctx = c.getContext("2d");
const mapTime = (value, x1, y1, x2, y2) => (value - x1) * (y2 - x2) / (y1 - x1) + x2;
setInterval(()=>{
ctx.beginPath();
ctx.arc(100, 100, 100, 1.5*Math.PI, mapTime(new Date().getSeconds(),0,360,0,60));
ctx.lineWidth = 10;
ctx.strokeStyle = "#FF0000";
ctx.stroke();
ctx.beginPath();
ctx.arc(100, 100, 80, 1.5*Math.PI, mapTime(new Date().getMinutes(),0,360,0,60));
ctx.lineWidth = 10;
ctx.strokeStyle = "#FFAA00";
ctx.stroke();
ctx.beginPath();
ctx.arc(100, 100, 60, 1.5*Math.PI, mapTime(new Date().getHours(),0,360,0,24));
ctx.lineWidth = 10;
ctx.strokeStyle = "#FFAAFF";
ctx.stroke();
},1000);
<canvas id="myCanvas"></canvas>
谢谢
解决方案
您需要在每一帧之后清除画布。在绘制函数的开头做这样的事情:
ctx.clearRect(0,0,c.width, c.height)
完整代码已验证正常工作:
c.width = window.innerWidth;
c.height = window.innerHeight;
var ctx = c.getContext("2d");
mapTime = (value, x1, y1, x2, y2) => (value - x1) * (y2 - x2) / (y1 - x1) + x2;
setInterval(()=>{
ctx.clearRect(0,0,c.width, c.height);
ctx.beginPath();
ctx.arc(100, 100, 100, 1.5*Math.PI, mapTime(new Date().getSeconds(),0,360,0,60));
ctx.lineWidth = 10;
ctx.strokeStyle = "#FF0000";
ctx.stroke();
ctx.beginPath();
ctx.arc(100, 100, 80, 1.5*Math.PI, mapTime(new Date().getMinutes(),0,360,0,60));
ctx.lineWidth = 10;
ctx.strokeStyle = "#FFAA00";
ctx.stroke();
ctx.beginPath();
ctx.arc(100, 100, 60, 1.5*Math.PI, mapTime(new Date().getMinutes(),0,360,0,24));
ctx.lineWidth = 10;
ctx.strokeStyle = "#FFAAFF";
ctx.stroke();
},1000);
推荐阅读
- tomcat - 在 grails 2.5 中安装 tomcat 9 的最佳方法是什么?
- python - Python selenium 获取由 javascript 添加的网页内容
- php - Learndash如何从课程ID中获取课程标题
- php - 使用 Ajax 将数据从 bootstrap modal 提交到 mySQL 数据库
- python - 数组python中2个相邻元素的平均值
- python - 点击事件清除
- reactjs - 反应材料用户界面错误不能作为后代出现
- excel - 从不依赖文件扩展名的 PowerScript 检查 Excel 文件格式
- xcode - 由于找不到“SocketRocket/NSRunLoop+SRWebSocket.h”文件,Jasonette Xcode 12.5 无法归档应用程序
- database - 基于gt和lt创建mongodb索引