4 回答

TA貢獻(xiàn)1785條經(jīng)驗(yàn) 獲得超8個(gè)贊
這樣做:如果您對(duì)代碼有任何疑問。隨意寫評(píng)論。
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貢獻(xiàn)1872條經(jīng)驗(yàn) 獲得超4個(gè)贊
我個(gè)人會(huì)選擇使用Array.prototype添加一個(gè)方法來獲取數(shù)組的隨機(jī)元素,然后使用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貢獻(xiàn)1851條經(jīng)驗(yàn) 獲得超5個(gè)贊
使用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貢獻(xiàn)1843條經(jīng)驗(yàn) 獲得超7個(gè)贊
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
添加回答
舉報(bào)