因此,對於我正在進行的項目,我希望有四個不同大小的畫布用四個球以相同的速度從牆上反彈。當所有的畫布尺寸相同時,代碼工作正常,但只要我嘗試調整畫布高度和寬度,球就會繼續在第一個畫布大小的區域內反彈。我不確定我做錯了什麼,我真的很感謝一些幫助。我相當新的JavaScript。彈跳在不同大小的畫布上的球javascript
下面是HTML:
<canvas id="canvas1" width="200" height="200"></canvas>
<canvas id="canvas2" width="200" height="400"></canvas>
<canvas id="canvas3" width="400" height="200"></canvas>
<canvas id="canvas4" width="200" height="200"></canvas>
這裏是JavaScript:
var canvas = document.getElementById("canvas1");
var ctx = canvas.getContext("2d");
var x = canvas.width/2;
var y = canvas.height-30;
var dx = -2;
var dy = 2;
var ballRadius = 10;
var canvas2 = document.getElementById("canvas2");
var ctx2 = canvas2.getContext("2d");
var x2 = canvas2.width/2;
var y2 = canvas2.height-30;
var canvas3 = document.getElementById("canvas3");
var ctx3 = canvas3.getContext("2d");
var x3 = canvas3.width/2;
var y3 = canvas3.height-30;
var canvas4 = document.getElementById("canvas4");
var ctx4 = canvas4.getContext("2d");
var x4 = canvas4.width/2;
var y4 = canvas4.height-30;
function drawBall() {
ctx.beginPath();
ctx.arc(x, y, ballRadius, 0, Math.PI*2);
ctx.fillStyle = "#0095DD";
ctx.fill();
ctx.closePath();
ctx2.beginPath();
ctx2.arc(x2, y2, ballRadius, 0, Math.PI*2);
ctx2.fillStyle = "#0095DD";
ctx2.fill();
ctx2.closePath();
ctx3.beginPath();
ctx3.arc(x3, y3, ballRadius, 0, Math.PI*2);
ctx3.fillStyle = "#0095DD";
ctx3.fill();
ctx3.closePath();
ctx4.beginPath();
ctx4.arc(x4, y4, ballRadius, 0, Math.PI*2);
ctx4.fillStyle = "#0095DD";
ctx4.fill();
ctx4.closePath();
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx2.clearRect(0, 0, canvas2.width, canvas2.height);
ctx3.clearRect(0, 0, canvas3.width, canvas3.height);
ctx4.clearRect(0, 0, canvas4.width, canvas4.height);
drawBall();
x += dx;
y += dy;
x2 += dx;
y2 += dy;
x3 += dx;
y3 += dy;
x4 += dx;
y4 += dy;
if(y + dy > canvas.height-ballRadius || y + dy < ballRadius) {
dy = -dy; }
if(x + dx > canvas.width-ballRadius || x + dx < ballRadius) {
dx = -dx; }
if(y2 + dy > canvas2.height-ballRadius || y2 + dy < ballRadius) {
dy = -dy; }
if(x2 + dx > canvas2.width-ballRadius || x2 + dx < ballRadius) {
dx = -dx; }
if(y3 + dy > canvas3.height-ballRadius || y3 + dy < ballRadius) {
dy = -dy; }
if(x3 + dx > canvas3.width-ballRadius || x3 + dx < ballRadius) {
dx = -dx; }
if(y4 + dy > canvas4.height-ballRadius || y4 + dy < ballRadius) {
dy = -dy; }
if(x4 + dx > canvas4.width-ballRadius || x4 + dx < ballRadius) {
dx = -dx; }
}
setInterval(draw, 10);
謝謝,這有助於很多!肯定會閱讀有關requestAnimationFrame的內容。 @bfmags –