스크레이퍼 효과

html:


javascript 부분:
    function imageClip(filter){var canvas = document.querySelector('canvas'),
        context = canvas.getContext('2d'),
        img = new Image(), //     
        finish; //       

    img.src = 'http://www.jcore.cn/resources/images/2014/09/20/html5-series-clip-pic-0.png'; //     
    img.onload = function(e) //       
    {
        var imgw = img.width,  //    
            imgh = img.height, //    
            offsetX = canvas.offsetLeft, //       
            offsetY = canvas.offsetTop, //        
            mousedown = false; //     

        //    canvas  、 、  
        canvas.width  = imgw;
        canvas.height = imgh;
        canvas.style.backgroundImage = 'url('+img.src+')';

        //        、   
        context.fillStyle = 'gray';
        context.globalAlpha = 0.6;

        //     
        context.fillRect(0,0,imgw,imgh);

        //        canvas  
        context.globalCompositeOperation = 'destination-out';

        //       
        function eventDown(e){
            e.preventDefault(); //     
            mousedown = true; //        
        }

        //       
        function eventUp(e){
            e.preventDefault(); //     
            mousedown = false; //            
            clearMask(); //      
        }

        //        
        function clearMask(){
            var num = 0, //    
                datas = context.getImageData(0,0,imgw,imgh), //     
                datasLength = datas.data.length; //     
            for (var i = 0; i < datasLength; i++) {
                if (datas.data[i] == 0) num++; //  0     ,   ++
            }
            if (num >= datasLength * filter) { //              
                if(finish) finish(); //       
            };
        }

        //       
        function eventMove(e){
            e.preventDefault(); //     
            if(mousedown) {
                if(e.changedTouches){ //     
                    e = e.changedTouches[e.changedTouches.length-1];
                }
                var x = (e.clientX + document.body.scrollLeft || e.pageX) - offsetX || 0, // X   
                    y = (e.clientY + document.body.scrollTop  || e.pageY) - offsetY || 0; // Y   

                //      
                context.beginPath();
                context.arc(x, y, 30, 0, Math.PI * 2); //   
                context.fill();
            }
        }

        //       
        canvas.addEventListener('touchstart', eventDown);
        canvas.addEventListener('touchend', eventUp);
        canvas.addEventListener('touchmove', eventMove);
        //        
        canvas.addEventListener('mousedown', eventDown);
        canvas.addEventListener('mouseup', eventUp);
        canvas.addEventListener('mousemove', eventMove);
    };

    this.finish = function(callback){
        finish = callback;
    }
}

호출 방법:
var clip = new imageClip(0.1);
clip.finish(function(){
alert("clip success...");
});

좋은 웹페이지 즐겨찾기