var canvas = document.createElement("canvas");
b = canvas.getContext("2d");
canvas.id = "canvas"
canvas.width = 900;
canvas.height = 600;
document.body.appendChild(canvas);
var posX = 430;
posY = 300;
var myArray = [-3.5,0,3.5];
var dX = myArray[Math.floor(Math.random()*myArray.length)];
var dY = myArray[Math.floor(Math.random()*myArray.length)];
setInterval(function (){
b.fillStyle = "steelblue";
b.fillRect(0, 0, canvas.width, canvas.height);
posX += dX;
posY += dY;
if (posX > 875){
dX = 0;
posX = 875;
}
if (posX < 5){
dx = 0;
posX = 5;
}
if (posY > 575){
dY = 0;
posY = 575;
}
if (posY < 5){
dY = 0;
posY = 5;
}
b.fillStyle = "snow";
b.fillRect(posX, posY, 20, 20);
}, 20)
这就是我的全部代码。我想随机移动背景上的立方体。现在它只向一个随机方向移动。但我希望它每秒都改变这个方向。因为 dX 和 dY 必须每秒改变一次。
慕的地10843
守着一只汪
江户川乱折腾
蓝山帝景
相关分类