gpt4 book ai didi

javascript - 在 Canvas 中沿相反方向移动矩形

转载 作者:行者123 更新时间:2023-11-30 16:58:18 25 4
gpt4 key购买 nike

请原谅这个问题,对 JS 来说是全新的。

我已经成功地在 Canvas 上来回移动了一个矩形,我想添加第二个相反的方式(甚至上下)

唯一的问题是第二个矩形是静态的,我无法让它移动。

我可以在第一个方 block 的相同函数中放置一个新的 ctx.fillRect(x,y,w,h) 吗?

作为 atm 它看起来像这样:

function drawSquare(ctx) {

clearCanvas(ctx);
ctx.fillStyle = "black";
ctx.fillRect(xpos, 140, 20, 20);
if(direction==="goright"){
if(xpos<canvasWidth - 20){xpos = xpos + 5;}else{direction = "left";}
} if(direction==="left"){
if(xpos>0){xpos = xpos - 5;}else{direction = "goright";}
}
// This is the second square i am having trouble with??
ctx.strokeStyle = "black";
ctx.strokeRect(780, 200, 20, 20)

if(direction==="goright"){
if(xpos<canvasWidth - 20){xpos = xpos + 5;}else{direction = "left";}
} if(direction==="left"){
if(xpos>0){xpos = xpos - 5;}else{direction = "goright";}
}

如果需要,我有自己的变量和其他编码。但是我需要为第二个方 block 设置第二个方向变量吗?或者我需要为它设置一个完全不同的函数和新的 setInterval 吗?

最佳答案

您需要在更新您的xpos 变量并使用您的xpos 变量后绘制第二个矩形。

function drawSquare(ctx) {
clearCanvas(ctx);
if(direction==="goright"){
if(xpos<canvasWidth - 20){xpos = xpos + 5;}else{direction = "left";}
} if(direction==="left"){
if(xpos>0){xpos = xpos - 5;}else{direction = "goright";}
}
ctx.fillStyle = "black";
ctx.fillRect(xpos, 140, 20, 20);

if(direction==="goright"){
if(xpos<canvasWidth - 20){xpos = xpos + 5;}else{direction = "left";}
} if(direction==="left"){
if(xpos>0){xpos = xpos - 5;}else{direction = "goright";}
}
// This is the second square i am having trouble with??
ctx.strokeStyle = "black";
ctx.strokeRect(xpos, 200, 20, 20)
}

这是一个工作片段

var
ctx = document.getElementById('c').getContext('2d'),
xpos = 0, t,
canvasWidth = 256,
direction = "goright"
;

function drawSquare(ctx) {
ctx.clearRect(0,0,256,256);
if(direction==="goright"){
if(xpos<canvasWidth - 20){xpos = xpos + 5;}else{direction = "left";}
} if(direction==="left"){
if(xpos>0){xpos = xpos - 5;}else{direction = "goright";}
}
ctx.fillStyle = "black";
ctx.fillRect(xpos, 140, 20, 20);

if(direction==="goright"){
if(xpos<canvasWidth - 20){xpos = xpos + 5;}else{direction = "left";}
} if(direction==="left"){
if(xpos>0){xpos = xpos - 5;}else{direction = "goright";}
}
// This is the second square i am having trouble with??
ctx.strokeStyle = "black";
t = window.performance.now();
ctx.strokeRect(xpos + Math.cos(t * 0.001) * 32, Math.sin(t * 0.001) * 118 + 128, 20, 20)
}

window.requestAnimationFrame(function draw() {
drawSquare(ctx);
window.requestAnimationFrame(draw);
});
<canvas width="256" height="256" id="c"></canvas>

关于javascript - 在 Canvas 中沿相反方向移动矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29292416/

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