我在文本编辑器上写了以下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>
我画的代码应该显示一个从左到右移动的圆圈,但由于某种原因,只剩下背景。
有人可以告诉我我做错了什么,拜托并谢谢你。
答案 0 :(得分:1)
定义您的功能drawCircle()
后,您忘了拨打它并移动您的圈子,您必须使用setInterval
来有效地调用此功能
在您的脚本中setInterval(drawCircle, 1000);
之后添加function drawCircle() {...}
。