Versionsvergleich
Aus ProgrammingWiki
Vergleich: 2019-11-25T15:27:29+00:00 → 2019-11-29T13:18:58+00:00
<language>Javascript</language> | |
| − | <code id="5ddbf2e11ed12"> |
| − | var canvas; |
| − | var context; |
| − | var blocks; |
| − | function Box(y, color, speed) { |
| + | |
| + | <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.a = 25; |
| − | this.y = y; |
| − | this.color = color; |
| + | this.y = yStart; |
this.speed = speed; | |
| − | |
| + | this.size = SIZE; |
| + | |
| + | // renders the box with the given specifications to the canvas |
this.render = function() { | |
| − | context.fillColor(this.color); |
| − | context.fillRect(this.x, this.y, this.width, this.width, this.color); |
| − | } |
| + | canvas.setColor(0, 0, 0); |
| + | canvas.fillRect(this.x, this.y, this.size, this.size); |
| + | }; |
} | |
function init() { | |
| − | canvas = new Canvas(1); |
| − | context = canvas.getContext("2D"); |
| − | console.log("Lasset das wahnsinnige Spektakel beginnen."); |
| + | // 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() { | |
| − | blocks.forEach(function(block) { |
| − | block["y"] += block["speed"]; |
| + | 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() { | |
| − | blocks.forEach(function(block) { |
| − | block.render(); |
| + | // render |
| + | canvas.setColor(255, 255, 255); |
| + | canvas.fillRect(0, 0, 400, 400); |
| + | |
| + | boxes.forEach(function(box) { |
| + | box.render(); |
}); | |
} | |
| − | function loopAnimation() { |
| − | tick(); |
| − | render(); |
| − | } |
| − | |
init(); | |
| − | runInterval("loopAnimation", 12); |
| − | |
| − | </code> |
| − | |
| − | <run id="5ddbf2e11edb0"> |
| − | |
| + | loop(); |
</run> | |
<canvas w=600, h=300> </canvas> |