我想模拟一盒随机移动的球。 我创造了一个只有一个移动球的画布。 我想将球复制到其他球中,以便它们可以从特定方向开始并独立地随机移动。 下面的代码用于创建1个移动球的画布。 你能帮助我复制球并让它们随机移动吗?
我使用的是Javascript,HTML5和PHP。强调文字
谢谢。
<html>
<head>
<style>
canvas { margin:0 20px 10px 200px; width:700; height:400; border:solid #CC0000; border-radius:15px;}
</style>
<canvas id="move"></canvas>
<script type="text/javascript">
var canvas = document.getElementById('move');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var x = canvas.width / 2 + 100; //starting position
var y = canvas.height / 2 + 100;
var ball = canvas.getContext('2d');
ball.fillStyle = '#FF0000'; //color
var radius = 30;
var dx = 10;
var dy = 10;
var delta = 55; // range (from 0) of possible dx or dy change
var max = 215; // maximum dx or dy values
canvas.addEventListener("click", togglestart);
function togglestart() {
if (interval == undefined) interval = window.setInterval(animate, 10000 / 60); // 60 FPS
else {
interval = clearInterval(interval);
console.log(interval);
}
}
var interval = window.setInterval(animate, 1000 / 60);
function animate() {
var d2x = (Math.random() * delta - delta / 2); //change dx and dy by random value
var d2y = (Math.random() * delta - delta / 2);
if (Math.abs(d2x + dx) > max) // start slowing down if going too fast
d2x *= -1;
if (Math.abs(d2y + dy) > max) d2y *= -1;
dx += d2x;
dy += d2y;
if ((x + dx) < 0 || (x + dx) > canvas.width) // bounce off walls
dx *= -1;
if ((y + dy) < 0 || (y + dy) > canvas.height) dy *= -1;
x += dx;
y += dy;
ball.beginPath(); //drawing ball
ball.arc(x, y, radius, 0, 2 * Math.PI, false);
ball.clearRect(0, 0, canvas.width, canvas.height); // CLS clear the canvas
ball.fill();
}
</script>
</head>
</html>