gpt4 book ai didi

javascript - 围绕 Canvas 边缘移动的圆圈

转载 作者:行者123 更新时间:2023-11-30 19:10:04 26 4
gpt4 key购买 nike

我需要一个围绕 Canvas 边缘移动的圆圈。向右然后向下移动可以正常工作,但是当它需要向左移动时,它会跳到右下角并开始一次又一次地向右移动。我不知道如何解决这个问题。

  var can = document.getElementById('C4');
var ctx = can.getContext('2d');
var x = 5, y = 20;
ctx.fillStyle = "black";
ctx.fillRect(700, 100, 100, 100);
function draw() {
ctx.beginPath();
ctx.arc(x, y, 20, 0, 2 * Math.PI);
ctx.fillStyle = 'rgba(250,0,0,0.4)';
ctx.fill();
do {//moving right
x += 2;
} while (x <! 281);
if (x >= 280){//down
do {
x = 280;
y += 2;
} while (y <! 130);
}
if(y >= 130 && x >= 280){//left
do {
x = x - 2;
y = 130;
} while (x >! 20);
}
if (x <= 20) {//up
do {
x = 20;
y = y-2;
} while (y <! 20);
}

ctx.fillStyle = "rgba(34,45,23,0.4)";
ctx.fillRect(0, 0, can.width, can.height);
requestAnimationFrame(draw);
}
draw();
canvas { border: 1px solid black}
<canvas id="C4"></canvas>

最佳答案

由于您使用的是递归,因此不需要 do while,循环只是让圆从一个边跳到另一个边。您可以使用 if 条件实现您的目标,如下所示:

var can = document.getElementById('C4');
var ctx = can.getContext('2d');
var x = 5, y = 20;
ctx.fillStyle = "black";
ctx.fillRect(700, 100, 100, 100);
function draw() {
ctx.beginPath();
ctx.arc(x, y, 20, 0, 2 * Math.PI);
ctx.fillStyle = 'rgba(250,0,0,0.4)';
ctx.fill();

if (x < 280 && y == 20) {
x += 2;
}

if (x >= 280 && y < 130){//down
x = 280;
y += 2;
}

if(y >= 130 && x > 20){//left
x = x - 2;
y = 130;
}

if (x == 20 && y > 20) {//up
x = 20;
y = y-2;
}

ctx.fillStyle = "rgba(34,45,23,0.4)";
ctx.fillRect(0, 0, can.width, can.height);
requestAnimationFrame(draw);
}

draw();
canvas { border: 1px solid black}
<canvas id="C4"></canvas>

关于javascript - 围绕 Canvas 边缘移动的圆圈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58589335/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com