我正在尝试使用此代码在一条直线上绘制一个移动的圆圈。但是我提出了一个语法错误。帮我修改一下这段代码。
<script>
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
function draw_circle (circleX, circleY, radius, fill) {
context.fillStyle = "black";
context.fillRect(0, 0, 800, 300);
context.strokeStyle = "red";
context.strokeRect(5, 5, 790, 290);
var speed = 5
context.fillStyle = fill;
context.arc(circleX, circleY, radius, 0, Math.PI*2);
context.fill();
}
setInterval(draw_circle(100,100, 30 , "cyan"), 33);
</script>
答案 0 :(得分:1)
您必须清除画布(使用canvas.width = canvas.width
或clearRect()
)
请注意,您必须添加context.beginPath()
才能让clearRect()
完成工作。
完成后,您只需增加弧的x位置。
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
function draw_circle (circleX, circleY, radius, fill) {
//clear the canvas
context.clearRect(0,0,canvas.width, canvas.height);
context.beginPath();
context.fillStyle = "black";
context.fillRect(0, 0, 800, 300);
context.strokeStyle = "red";
context.strokeRect(5, 5, 790, 290);
var speed = 5;
//just a loop if you don't want it simply use `i+=speed;`
(i>canvas.width+radius)?i=(radius*-2):i+=speed;
context.fillStyle = fill;
context.arc(circleX, circleY, radius, 0, Math.PI*2);
context.fill();
}
var i=0;
setInterval(function(){draw_circle(i,100, 30 , "cyan")}, 33);
<canvas id = "myCanvas"></canvas>