4 回答

TA贡献1785条经验 获得超8个赞
这样做:如果您对代码有任何疑问。随意写评论。
const canvas = document.createElement('canvas')
canvas.width = 100
canvas.height = 100
canvas.style.backgroundColor = 'steelblue'
document.body.appendChild(canvas)
const ctx = canvas.getContext('2d')
const RADIUS = 5
const SPEED = 0.6
let pos = [canvas.width / 2, canvas.height / 2]
let direction = [0, 0]
setInterval(function() {
pos[0] += direction[0] * SPEED
pos[1] += direction[1] * SPEED
if(pos[0] <= RADIUS || pos[0] >= canvas.width - RADIUS ||
pos[1] <= RADIUS || pos[1] >= canvas.height - RADIUS) {
pos = [canvas.width / 2, canvas.height / 2]
}
ctx.clearRect(0, 0, canvas.width, canvas.height)
ctx.fillStyle = "snow"
ctx.fillRect(pos[0] - RADIUS, pos[1] - RADIUS, 2 * RADIUS, 2 * RADIUS)
}, 20)
setInterval(function() {
const randomAngle = Math.random() * 2 * Math.PI
direction = [Math.cos(randomAngle), Math.sin(randomAngle)]
}, 1000)

TA贡献1872条经验 获得超3个赞
我个人会选择使用Array.prototype添加一个方法来获取数组的随机元素,然后使用setInterval每秒更新值:
Array.prototype.getRandom = function() {
let index = Math.floor(Math.random() * this.length);
return this[index];
}
var myArray = [-3.5,0,3.5];
var dX, dY;
function updateDerivatives() {
dX = myArray.getRandom(),
dY = myArray.getRandom();
console.log("Updated values:", { dX, dY });
}
setInterval(updateDerivatives, 1000);

TA贡献1851条经验 获得超5个赞
使用setInterval()
https://javascript.info/settimeout-setinterval
var myArray = [-3.5,0,3.5];
var dX, dY
setInterval(() => {
dX = myArray[Math.floor(Math.random()*myArray.length)];
dY = myArray[Math.floor(Math.random()*myArray.length)];
}, 1000)

TA贡献1843条经验 获得超7个赞
var myArray = [-3.5,0,3.5];
var dX;
var dY;
setInterval(() => { // you could also use setInterval(function(){...},...)
dX = myArray[Math.floor(Math.random()*myArray.length)];
dY = myArray[Math.floor(Math.random()*myArray.length)];
}, 1000) // 1000 milliseconds
添加回答
举报