Versionsvergleich
Aus ProgrammingWiki
Vergleich: 2019-11-29T13:18:58+00:00 → 2019-11-29T13:18:58+00:00
<language>Javascript</language> | |
<run id="5ddbf2e11edb0"> | |
var canvas = new Canvas(1); | |
var requestId = -1; | |
var boxes; | |
const SIZE = 40, OFFSET = 10, SPEED_STEP = 4, BOX_AMOUNT = 8; | |
function Box(yStart, speed) { | |
this.x = 0; | |
this.y = yStart; | |
this.speed = speed; | |
this.size = SIZE; | |
// renders the box with the given specifications to the canvas | |
this.render = function() { | |
canvas.setColor(0, 0, 0); | |
canvas.fillRect(this.x, this.y, this.size, this.size); | |
}; | |
} | |
function init() { | |
// init boxes | |
boxes = new Array(BOX_AMOUNT); | |
for(var i = 0; i < boxes.length; i++) | |
boxes[i] = new Box(i * SIZE + OFFSET, (i + 1) * SPEED_STEP, ); | |
} | |
function loop() { | |
tick(); | |
render(); | |
setInterval(loop(), 200); | |
} | |
function tick() { | |
boxes.forEach(function(box) { | |
box.x += box.speed; | |
// if colliding with border, change direction | |
if(((box.x + box.size) > canvas.width) || (box.x < 0)) | |
box.speed *= -1; | |
}); | |
} | |
function render() { | |
// render | |
canvas.setColor(255, 255, 255); | |
canvas.fillRect(0, 0, 400, 400); | |
boxes.forEach(function(box) { | |
box.render(); | |
}); | |
} | |
init(); | |
loop(); | |
</run> | |
<canvas w=600, h=300> </canvas> |