在画布上从左向右直线移动圆圈

Moving circle in a straight line from left to the right of canvas

本文关键字:移动      更新时间:2023-09-26

我在这里试图用这段代码在直线上画一个移动的圆圈。但是我把语法放错了。帮助我更正此代码。

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

您必须清除画布(使用canvas.width = canvas.widthclearRect()

请注意,您必须添加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>