那些年 程序员的样子

高级版刮刮乐

2017-12-26  本文已影响23人  bo_bo_bo_la

判断当刮到一半的时候,自动显示全部内容

globalCompositeOperation

像素

我们使用getImageData()能够获取指定区域的像素值ImageData
ImageData中3个属性:width,height和data
width和height表示访问像素区域大小
data是一个包含访问区域所有像素信息的CanvasPixeArray

getImageData(x,y,width,height)
<script type="text/javascript">
        var canvas = document.getElementById("myCanvas");
        var context = canvas.getContext("2d");
        //目标图
        context.beginPath();
        context.fillStyle = "gray";
        context.fillRect(0,0,canvas.offsetWidth,canvas.offsetHeight);
        context.fill();
        context.globalCompositeOperation = "destination-out";
        canvas.onmousedown = function(e){
            var ev = window.event || e;
            var x = ev.clientX - canvas.offsetLeft;
            var y = ev.clientY - canvas.offsetTop;
            context.beginPath();
            context.moveTo(x,y);
            canvas.onmousemove = function(e){
                var ev = window.event || e;
                var xx = ev.clientX - canvas.offsetLeft;
                var yy = ev.clientY - canvas.offsetTop;
                context.lineTo(xx,yy);
                context.lineWidth = 30;
                context.stroke();
                all()
            }
        }
        function all(){
            var imageData = context.getImageData(0,0,canvas.offsetWidth,canvas.offsetHeight);
            var count = 0;
            for(var i = 0;i < imageData.data.length;i+=4){
                if(imageData.data[i+3] == 0){
                    count++;
                    if(count >= imageData.data.length/16) {
                        context.clearRect(0,0,canvas.offsetWidth,canvas.offsetHeight);
                    }
                }
            }
        }
        document.onmouseup = function(){
            canvas.onmousemove = "";
        }
    </script>
上一篇下一篇

猜你喜欢

热点阅读