gpt4 book ai didi

javascript - 在 Canvas 上移动元素

转载 作者:行者123 更新时间:2023-12-02 17:52:02 25 4
gpt4 key购买 nike

有谁知道为什么这两个矩形不移动?

http://jsfiddle.net/tmyie/R5wx8/

var canvas = document.getElementById('canvas'),
c = canvas.getContext('2d');

function move() {

var x = 10,
y = 15;

c.fillRect(x, y, 5, 5),
c.fillRect(y, x, 25, 55);
x++;
y++;
}

setInterval(move, 300);

最佳答案

每次 move 方法运行时,您都会再次声明 x 和 y 为 10 和 15。将 x 和 y 的声明放在方法外部以使矩形移动。

var canvas = document.getElementById('canvas'),
c = canvas.getContext('2d');


var x = 10;
var y = 15;

function move() {
c.fillRect(x, y, 5, 5),
c.fillRect(x, y, 15, 15);
x++;
y++;
}

setInterval(move, 300);

关于javascript - 在 Canvas 上移动元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21270130/

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