Fetch image

http://stackoverflow.com/questions/164181/how-to-fetch-a-remote-image-to-display-in-a-canvas

by tokkonoPapa

HTML

<input type="button" value="stop" onclick="stop()">
<p id="title"></p>
<canvas width="300px" height="200px" id="canvas"></canvas>

JavaScript

function copyCanvas(img) {
    var canvas = document.getElementById('canvas');
    var ctx = canvas.getContext('2d');
    ctx.drawImage(img, 0, 0);
}

function loadImage() {
    var img = new Image();
    img.onload = function () {
        copyCanvas(img);
    };
    var src = "http://lorempixel.com/300/200/sports/" + randomText() + "/";
    img.src = src;
    document.getElementById('title').innerHTML = src;
}

function randomText() {
    var c, i, j = '';
    for (i = 0; i < 4; i++) {
        c = Math.floor(Math.random() * 26);
        j += String.fromCharCode(c + 65);
    }
    return j;
}

var timer = 0;

window.onload = function () {
    loadImage();
    timer = setInterval(loadImage, 1500);
};

function stop() {
    if (timer) {
        clearInterval(timer);
    }
}