I try to squeeze every last bit of performance out of my game on canvas; I recently found out that cleaning the canvas is very difficult, so I'm trying to find a way to replace cleaning the entire canvas in each frame. However, I find a few problems with the new method that I am trying to do to clear each bounding object object separately and then update them.
The problem is that the elements remain โleftโ when they leave the canvas, and part of the image remains. I tried to simplify the code to make sure that the problem is not with the rest of the code, and there is no joy.
Returning to wiping the entire canvas, each frame is also undesirable, especially since this new method is much faster. Here's the code (for some reason, it doesn't work like a fiddle ).
var enemyCtx = document.getElementById('enemy').getContext('2d'); var game = { w: 800, h: 500 }; var enemies = []; window.addEventListener('load', function() { for (var i = 0; i < 200; i++) { enemies[enemies.length] = new Enemy(); } update(); }, false); var buffer = document.createElement('canvas'); buffer.width = 42; buffer.height = 42; var bufferCtx = buffer.getContext('2d'); drawEnemy(bufferCtx, 5, 5, 32, 32, 'red'); function update() { for (var i = 0; i < enemies.length; i++) { enemyCtx.clearRect( enemies[i].x, enemies[i].y, enemies[i].x + enemies[i].width, enemies[i].y + enemies[i].height); } for (var i = 0; i < enemies.length; i++) { enemies[i].x-=5; enemyCtx.drawImage(buffer, enemies[i].x-5, enemies[i].y-5); } requestAnimationFrame(update); } function drawEnemy(ctx, x, y, width, height, colour) { ctx.lineWidth = 1; ctx.strokeStyle = colour; ctx.strokeRect(x + 0.5, y + 0.5, width, height); } function Enemy() { this.x = Math.random()*game.w; this.y = Math.random()*game.h; this.width = 32; this.height = 32; } (function() {
& HTML:
<canvas id="enemy" width="800" height="500"></canvas>โ
Any insights you guys could give me would be very helpful; thanks!