DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> 關於JavaScript >> javascript+canvas制作九宮格小程序
javascript+canvas制作九宮格小程序
編輯:關於JavaScript     

js核心代碼

復制代碼 代碼如下:
/*
 *canvasid:html canvas標簽id
 *imageid:html img 標簽id
 *gridcountX:x軸圖片分割個數
 *gridcountY:y軸圖片分割個數
 *gridspace:宮格空隙
 *offsetX:x*y宮格相對canvas(0,0)X坐標偏移量
 **offsetX:x*y宮格相對canvas(0,0)Y坐標偏移量
 *isanimat:是否啟用動畫顯示
 */
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;
    //動畫
    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 { //非動畫
        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代碼

復制代碼 代碼如下:
<canvas id="canvas1" width="900px" height="550px">Canvas demo</canvas>
 <img id="image1" style="display:none" src="http://files.jb51.net/file_images/article/201412/2014122894620636.jpg"/>

使用方法:

復制代碼 代碼如下:
//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

代碼很簡潔,效果卻非常炫酷,小伙伴們學會了嗎?

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved