答案 0 :(得分:0)
假设你想要作为gif。
容易做到。创建一个tile数组。只是每个瓷砖的位置和宽度。然后从该阵列中随机移除一块瓷砖并将其淡入。当淡入时,获取下一个瓷砖,直到没有更多。
// helper functions
var imageTools = (function () {
var tools = {
canvas : function (width, height) { // create a blank image (canvas)
var c = document.createElement("canvas");
c.width = width;
c.height = height;
return c;
},
loadImage : function (url, cb) { // cb is calback. Check first argument for status
var i = new Image();
i.src = url;
i.addEventListener('load', cb);
i.addEventListener('error', cb);
return i;
},
};
return tools;
})();
var canvas = imageTools.canvas(300,150); // create default canvas
var ctx = canvas.getContext("2d");
document.body.appendChild(canvas);
// set up tile data
const hTiles = 8; // horizontal and width tiles counts
const wTiles = 8;
const fadeTime = 400; // in ms 1/1000 second
var tiles=[]; // array of tiles
// adds tile to array
function addTile(x,y,w,h){
tiles.push({
x : x,
y : y,
w : w,
h : h,
});
}
// load image with callback function to cut up image into tiles
var img = imageTools.loadImage("http://i.stack.imgur.com/lMsn0.jpg", function(){
// get image size
var w = this.width;
var h = this.height;
// resize ccanvas to fit image
canvas.width = w;
canvas.height = h;
// get tile size
var ww = w / wTiles;
var hh = h / hTiles;
// add all tiles to the tile list
for(var y = 0; y < hTiles; y += 1){
for(var x = 0; x < wTiles; x += 1){
// need to be careful with rounding
addTile(
Math.floor(x * ww),
Math.floor(y*hh),
Math.floor((x + 1) * ww) - Math.floor(x * ww),
Math.floor((y + 1) * hh) - Math.floor(y * hh)
);
}
}
this.ready = true;
})
var globalTime; // global to this
var tile = null; // hold currently fading tile
var allDone;
// main update function
function update(timer){
globalTime = timer;
ctx.setTransform(1,0,0,1,0,0); // reset transform
ctx.globalAlpha = 1; // reset alpha
// Start tiles when img is complete. Ie loaded
if(img.ready){
if(tile === null){ // need a tile
if(tiles.length > 0){ // are there any tiles left
// remove a random tile from the array of tiles.
tile = tiles.splice(Math.floor(Math.random() * tiles.length),1)[0];
tile.startTime = globalTime; // set the start time
}else{ // all done
// just exit to stop
ctx.font = "28px arial black";
ctx.fillText("All done!",10,30);
return;
}
}
if(tile !== null){
var f = (globalTime-tile.startTime) / fadeTime; // get normalised fade time
if(f >= 1){ // all done with this tile. draw it and setup for the next
ctx.drawImage(img,tile.x,tile.y,tile.w,tile.h,tile.x,tile.y,tile.w,tile.h);
tile = null;
}else{
// clear background for this tile
ctx.clearRect(tile.x,tile.y,tile.w,tile.h);
ctx.globalAlpha = f; // Just set to the alpha
// draw the tile
ctx.drawImage(img,tile.x,tile.y,tile.w,tile.h,tile.x,tile.y,tile.w,tile.h);
}
}
}
requestAnimationFrame(update);
}
requestAnimationFrame(update);