Onload vs Manual Canvas generation

by Eric

HTML

<script src="http://fonts.googleapis.com/css?family=Ruda:400,700|Ubuntu:400,700,400italic,700italic|Ubuntu+Mono:400,700,400italic,700italic"></script>
<canvas class="onload-canvas"></canvas>

<br />
<a href="#0" class="gen-mancan">Generate Canvas</a>
<br />
<canvas class="man-canvas"></canvas>

CSS

canvas
{
    border: 1px solid #000000;
}

JavaScript

generateCanvas($('.onload-canvas')[0]);

$('.gen-mancan').on('click', function() {
     generateCanvas($('.man-canvas')[0]);
});

function generateCanvas(element)
{
    var context = element.getContext('2d');
    
    // Clear the canvas to redraw
    // Store the current transformation matrix
    context.save();
    
    // Use the identity matrix while clearing the canvas
    context.setTransform(1, 0, 0, 1, 0, 0);
    context.clearRect(0, 0, element.width, element.height);
    
    // Restore the transform
    context.restore();

    
    resolveRetina(element);
    //context.scale(window.devicePixelRatio, window.devicePixelRatio);
    
    // Draw text
    context.font = '12px Ubuntu';
    context.fillStyle = '#000000';
    
    context.textBaseline = 'alphabetic';
    context.fillText(
        'top', 
        20, 
        15
    );
    
    context.textBaseline = 'middle';
    context.fillText(
        'middle', 
        20, 
        30
    );
    
    context.textBaseline = 'alphabetic';
    context.fillText(
        'alphabetic', 
        20, 
        55
    );
    
    
}


function resolveRetina(element)
{
    var context = element.getContext('2d');
    
    // finally query the various pixel ratios
    var devicePixelRatio = window.devicePixelRatio || 1,
    backingStoreRatio = context.webkitBackingStorePixelRatio ||
    context.mozBackingStorePixelRatio ||
    context.msBackingStorePixelRatio ||
    context.oBackingStorePixelRatio ||
    context.backingStorePixelRatio || 1,
    
    ratio = devicePixelRatio / backingStoreRatio;
    
    console.log('dpr: ' + devicePixelRatio + ' - bsr: ' + backingStoreRatio + ' - ratio: ' + ratio);
    
    // ensure we have a value set for auto.
    // If auto is set to false then we
    // will simply not upscale the canvas
    // and the default behaviour will be maintained
    if (typeof auto === 'undefined') {
        auto = true;
    }
    
    // upscale the canvas if the two ratios don't match
    if (auto &&...