我在文本编辑器上编写了以下html代码:
window.onload = function() {
var canvasC = document.getElementById("canvasCircle");
var contextC = canvasC.getContext("2d");
var canvasBG = document.getElementById("canvasBackground");
var contextBG = canvasBG.getContext("2d");
var xPos = 50;
var yPos = canvasC.height / 2;
var radius = 40;
var endXPos = canvasC.width - 75;
var change = 10;
var startAngle = (Math.PI / 180) * 0;
var interval = 80;
var endAngle = (Math.PI / 180) * 360;
contextBG.fillStyle = "silver";
contextBG.fillRect(0, 0, canvasBG.width, canvasBG.height);
var intervalID = setInterval
function drawCircle() {
contextC.clearRect(0, 0, canvasC.width, canvasC.height);
contextC.strokeStyle = "green";
contextC.lineWidth = 4;
contextC.shadowOffsetX = 3;
contextC.shadowOffsetY = 3;
contextC.shadowBlur = 5;
contextC.shadowColor = "grey";
xPos += change;
if (xPos > endXPos) {
clearInterval(intervalID)
};
contextC.beginPath();
contextC.arc(xPos, yPos, radius, startAngle, endAngle, true);
contextC.stroke();
}
}
<div>
<canvas id="canvasCircle" width="400" height="125" style="border:2px solid black; position:absolute; left:auto; top:auto; z-index: 2">
Your browser doesn't currently support HTML5 Canvas.
</canvas>
<canvas id="canvasBackground" width="400" height="125" style="border:2px solid black; position:absolute; left:auto; top:auto; z-index: 1">
Your browser doesn't currently support HTML5 Canvas.
</canvas>
</div>
我绘制的代码应该显示一个从左到右移动的圆,但是由于某种原因,只保留了背景。有人可以告诉我我做错了什么吗,请谢谢。
最佳答案
定义函数drawCircle()
后,您忘记了调用它,并且为了移动圆环,必须使用setInterval
有争议地调用此函数
在脚本的setInterval(drawCircle, 1000);
之后添加function drawCircle() {...}
。