首页 > 解决方案 > 如何在值后更新画布?

问题描述

我正在尝试使用香草 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>

谢谢

标签: javascripthtmlcanvas

解决方案


您需要在每一帧之后清除画布。在绘制函数的开头做这样的事情:

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);

推荐阅读