Split an image using javascript

html5-canvas, javascript

Solution

You can use the clipping parameters of the drawImage() method and draw your clipped image onto a dynamically created canvas.

An example could be:

function getClippedRegion(image, x, y, width, height) {

    var canvas = document.createElement('canvas'),
        ctx = canvas.getContext('2d');

    canvas.width = width;
    canvas.height = height;

    //                   source region         dest. region
    ctx.drawImage(image, x, y, width, height,  0, 0, width, height);

    return canvas;
}

This will return a canvas element with the clipped image drawn in already. You can now use the canvas directly to draw it onto another canvas.

Example of usage; in your main code you can do:

var canvas = document.getElementById('myScreenCanvas'),
    ctx    = canvas.getContext('2d'),
    image  = document.getElementById('myImageId'),
    clip   = getClippedRegion(image, 50, 20, 100, 100);

// draw the clipped image onto the on-screen canvas
ctx.drawImage(clip, canvas.width * Math.random(), canvas.height * Math.random());

Problem

How to get a sections of a single image using javascript and store it in an array, and later display randomly on html5 canvas.

Original source