Prerendered-starfield

Benchmark created by Pascal Rettig on


Preparation HTML

<canvas id='game' width='480' height='320'>
</canvas>

Setup

var canvas = document.getElementById('game')
    var width = canvas.width;
    var height = canvas.height;
    
    var ctx = canvas.getContext('2d');
    
    // Set up the offscreen canvas
    var stars = document.createElement("canvas");
    stars.width = width;
    stars.height = height;
    var starCtx = stars.getContext("2d");
    
    
    
    // If the clear option is set, 
    // make the background black instead of transparent
    
      starCtx.fillStyle = "#000";
      starCtx.fillRect(0, 0, stars.width, stars.height);
    
    // Now draw a bunch of random 2 pixel
    // rectangles onto the offscreen canvas
    starCtx.fillStyle = "#FFF";
    starCtx.globalAlpha = 0.8;
    for (var i = 0; i < numStars; i++) {
      starCtx.fillRect(Math.floor(Math.random() * stars.width), Math.floor(Math.random() * stars.height), 2, 2);
    }
    
    var offset = 120;
    var draw = function() {
        var intOffset = Math.floor(offset);
        var remaining = stars.height - intOffset;
    
        // Draw the top half of the starfield
        if (intOffset > 0) {
          ctx.drawImage(stars, 0, remaining, stars.width, intOffset, 0, 0, stars.width, intOffset);
        }
    
        // Draw the bottom half of the starfield
        if (remaining > 0) {
          ctx.drawImage(stars, 0, 0, stars.width, remaining, 0, intOffset, stars.width, remaining);
        }
        }
        
        
        
    var starList = [];
    var numStars = 200;
    
    for (var i = 0; i < numStars; i++) {
      starList.push([Math.floor(Math.random() * stars.width), Math.floor(Math.random() * stars.height)]);
    
    }
    
    var drawStars = function(opacity) {
    
        // Now draw a bunch of random 2 pixel
        // rectangles onto the offscreen canvas
        ctx.fillStyle = "#FFF";
        ctx.globalAlpha = opacity;
        for (var i = 0; i < numStars; i++) {
          ctx.fillRect(starList[i][0], starList[i][1], 2, 2);
        }
    
        }

Test runner

Ready to run.

Testing in
TestOps/sec
prerender + blits
draw();
offset = 10;
draw();
offset = 200;
draw();
ready
50 individual stars
numStars = 50; 
ctx.clearRect(0,0,stars.width,stars.height);
drawStars(1);
drawStars(0.4);
drawStars(0.8);
ready
100 individual stars
numStars = 100; 
ctx.clearRect(0,0,stars.width,stars.height);
drawStars(1);
drawStars(0.4);
drawStars(0.8);
ready
100 individual stars + width
numStars = 100; 
canvas.width = width;
drawStars(1);
drawStars(0.4);
drawStars(0.8);
ready
200 individual stars
numStars = 200; 
ctx.clearRect(0,0,stars.width,stars.height);
drawStars(1);
drawStars(0.4);
drawStars(0.8);
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.

  • Revision 1: published by Pascal Rettig on