Javascript + canvas: Create a nine-palace code, canvas
Js core code
Copy codeThe Code is as follows:
/*
* Canvasid: id of the html canvas tag
* Imageid: id of the html img tag
* GridcountX: Number of image shards on the X axis
* GridcountY: Number of image shards on the Y axis
* Gridspace: space of the palace Lattice
* OffsetX: x * y coordinate offset of the grid relative to canvas (0, 0) X
** OffsetX: x * y coordinate offset of the palace lattice relative to canvas () Y
* 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-animated
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
Copy codeThe Code is as follows:
<Canvas id = "canvas1" width = "900px" height = "550px"> Canvas demo </canvas>
Usage:
Copy codeThe Code 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 concise, but the effect is cool. Have you learned it?