马赛克切换(切片) 2

真正的马赛卡效果

by 孙 超

HTML

<input type="button" value="下一张" id="btn_next" />
<div id="box">
</div>

CSS

*{
		margin:0;
		padding:0;
	}
	#box{
		margin:0px auto;
		width:500px;
		height:400px;
	}
	#box span{
		float:left;
	}

JavaScript

var imgs = [
    "https://st-gdx.dancf.com/templets/81315/shots/20190318-214917-qMqMe.png?x-oss-process=image/resize,w_276/interlace,1",
    "https://st-gdx.dancf.com/templets/81738/shots/20190124-161550-MxH49.png?x-oss-process=image/resize,w_276/interlace,1"
];

window.onload = function(){

    var rows = 20;
    var cols = 20;
    
    var box = document.getElementById("box");
    var width = box.offsetWidth / cols;
    var height = box.offsetHeight / rows;
    
    var timer = null;
    var now = 0; 
    var aSpan = [];
    
    for (var r=0; r<rows ;r++ ) {
        aSpan[r] = [];
        
        for (var c=0; c<cols ; c++ ) {
            var oSpan = document.createElement("span");
            aSpan[r][c] = oSpan;
            
            oSpan.style.backgroundImage = "url(" + imgs[0] + ")";
            oSpan.style.width = width + "px";
            oSpan.style.height = height + "px";
            
            box.appendChild(oSpan);
            
            var left = c * width;
            var top = r * height;
            oSpan.style.left = left + "px";
            oSpan.style.top = top + "px";
            
            oSpan.style.backgroundPosition = "-"+ left + "px -" + top + "px";
        }
    }
    
    // 是否可以切换
    var ready = true;
    var btn = document.getElementById("btn_next");
    btn.onclick = function(){
        
        // 完成当前动作之前不能切换
        if(!ready){
            return;
        }
        ready = false;
        
        now++;
        if(now == imgs.length){
            now = 0;
        }
        var count = 0;
        var len = box.children.length;
        
        for(var r = 0; r < rows; r++){
            for (var c = 0; c < cols ; c++ ) {
                (function(r, c){
                    
                    // 这种处理方式比较巧妙,用时间差来实现效果 !!!
                    setTimeout(function(){
                        aSpan[r][c].style.backgroundImage = "url("+ imgs[now] +")";
                        if(count++ == len - 1){
                        ...