Drawing an Image to the Canvas

by Denise Nepraunig

HTML

<div id="background">
    <canvas id="canvas" width="500" height="500"></canvas>
</div>

CSS

body {
    background: #CEF;
}
#background {
    width: 500px;
    height: 500px;
    background-image: url('http://www.nepraunig.com/canvas/deniseinsta.jpg');
}
#canvas {
}

JavaScript

// Grab the Canvas and Drawing Context
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');

// Create an image element
var img = document.createElement('IMG');

// When the image is loaded, draw it
img.onload = function () {
    ctx.drawImage(img, 0, 0);
    getSquareSize();
}

// Specify the src to load the image

// QR Code has the size of 500 x 500 px
//img.src = "http://www.nepraunig.com/canvas/pinterestqr.png";
img.src = "https://chart.googleapis.com/chart?chs=500x500&cht=qr&chl=http://www.nepraunig.com&choe=UTF-8&chld=H"

function getSquareSize() {
    // get the size of one square from the qr code
    // move from 0,0 diagonally -> f(x) = x
    // first comes white, then comes black, than comes white again, and then this 'black'
    // is the distance

    // algorithm to get pixel values per x,y

    var imageHeight = 500;
    var imageWidth = 500;

    //var imageData = ctx.getImageData(imageX, imageY, imageWidth, imageHeight);
    var imageData = ctx.getImageData(0, 0, 500, 500);
    var data = imageData.data;

    var firstcolorchange = false;
    var blackbegin = 0;
    var blackend = 0;
    var qrcodebegin = 0;
    var blocksize = 0;
    var secondcolorchange = false;
    var colorvalue; // get colorvalue from the red pixel
    var y, x = 0;

    // get the blocksize and the beginning of the qr code (=blackbegin)

    for (var i = 0; i < imageHeight; i++) {
        y = x = i;
        colorvalue = data[((imageWidth * y) + x) * 4];

        // color hasn't changed
        if (!firstcolorchange) {
            // if we "find" black:
            if (colorvalue < 128) {
                firstcolorchange = true;
                // remember where black begins
                blackbegin = i;
                qrcodebegin = blackbegin;
            }
        }

        if (firstcolorchange && !secondcolorchange) {
            // if we find white again
            if (colorvalue > 128) {
                blackend = i;
               ...