So für ein Projekt, ich arbeite an, würde ich gerne vier unterschiedlich große Leinwände mit vier Kugeln von der Wand mit der gleichen Geschwindigkeit abprallen. Der Code funktioniert gut, wenn alle Leinwände die gleiche Größe haben, aber sobald ich versuche, die Höhe und Breite der Leinwände anzupassen, springt der Ball weiter in einem Bereich der Größe der ersten Leinwand. Ich bin nicht sicher, was ich falsch mache, und ich würde wirklich etwas Hilfe schätzen. Ich bin ziemlich neu in Javascript. HierBall in verschiedenen Größen Leinwand javascript
ist die 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>
Und hier ist das 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);
Danke, das hilft viel! Wird sicher über requestAnimationFrame lesen. @bfmags –