js core code
The code copy is as follows:
/*
*canvasid:html canvas tag id
*imageid:html img tag id
*gridcountX: x-axis picture segmentation number
*gridcountY: the number of y-axis image segmentation
*gridspace: Grid space
*offsetX: x*y grid relative to canvas(0, 0) X coordinate offset
**offsetX: x*y grid relative to canvas(0, 0) Y coordinate offset
*isanimat: Whether to enable animation display
*/
function ImageGrid(canvasid, imageid, gridcountX, gridcountY, gridspace, offsetX, offsetY, isanimat) {
var image = new Image();
var g = document.getElementById(canvasid).getContext("2d");
var img=document.getElementById(imageid);
image.src=img.getAttribute("src");
g.drawImage(image, 0, 0);
var imagedata = g.getImageData(0, 0, image.width, image.height);
var grid_width = imagedata.width / gridcountX;
var grid_height = imagedata.height / gridcountY;
//Animation
if (isanimat) {
var x = 0,
y = 0;
var inter = setInterval(function() {
g.putImageData(imagedata, gridspace * x + offsetX, gridspace * y + offsetY, grid_width * x, grid_height * y, grid_width, grid_height);
x < gridcountX ? x++ : x = 0;
if (x == 0) {
y < gridcountY ? y++ : y = 0;
}
}, 200);
y == gridcountY ? clearInterval(inter) : null;
} else { //Non-animation
for (var y = 0; y < gridcountY; y++) {
for (var x = 0; x < gridcountX; x++) {
g.putImageData(imagedata, gridspace * x + offsetX, gridspace * y + offsetY, grid_width * x, grid_height * y, grid_width, grid_height);
}
}
}
}
html code
The code copy is as follows:
<canvas id="canvas1">Canvas demo</canvas>
<img id="image1" style="display:none" src="//files.VeVB.COM/file_images/article/201412/2014122894620636.jpg"/>
How to use:
The code copy is as follows:
//eg...
ImageGrid("canvas1", "image1", 3, 3, 2, 220, 0, true); //3*3
ImageGrid("canvas1", "image1", 4, 4, 2, 440, 0, true); //4*4
ImageGrid("canvas1", "image1", 3, 4, 2, 660, 0, false); //3*4
The code is very concise, but the effect is very cool. Have you learned it?