Home > Web Front-end > JS Tutorial > body text

Using javascript canvas to create a nine-square grid applet_javascript skills

WBOY
Release: 2016-05-16 16:24:02
Original
2022 people have browsed it

js core code

Copy code The code is as follows:

/*
*canvasid:html canvas tag id
*imageid:html img tag id
*gridcountX: Number of x-axis image divisions
*gridcountY: number of y-axis image divisions
*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-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 code The code is as follows:

Canvas demo

How to use:

Copy code The 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 very simple, but the effect is very cool. Have you guys learned it?

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!