画布透明蒙版效果百分比蒙版

时间:2016-03-16 12:26:29

标签: javascript html5 canvas

我在页面上覆盖了一个隐藏下面内容的画布。然后在鼠标移动时使用我清除图像叠加层以显示下面的内容,就像它被擦除一样。

我添加了一个每秒调用一次函数的计时器事件。

我正在努力的是如何使用此功能来检测已清除的百分比。因此,当超过75%的画布被清除时,我们可以触发一个函数。

这是一个jsfiddle https://jsfiddle.net/barrydowd/phgos32w/1/

这是代码

<html>
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no" />

    <style>
        p {position:absolute;top:0px;left:0px;width:400px;height:300px;}
        #c {position:absolute;top:0px;left:0px; cursor: url(http://findicons.com/files/icons/2232/wireframe_mono/48/cursor_arrow.png), auto;}
    </style>

    <script type="text/javascript">

    var ctx = "";
    var img = "";

    function get_cleared() {
        //DO SOMETHING HERE TO GET THE PERCETAGE OF CANVAS CLEARED
    }

    function init() {
        var int=self.setInterval(function(){get_cleared()},1000);
        var canvas = document.getElementById('c');
        ctx = canvas.getContext('2d');

        img = document.createElement('IMG');

        img.onload = function () {
            ctx.beginPath();
            ctx.drawImage(img, 0, 0);
            ctx.closePath();    
            ctx.globalCompositeOperation = 'destination-out';    
        }

        img.src = "http://dl.dropbox.com/u/12501653/FROST.png";

        function drawPoint(pointX,pointY){
            var grd = ctx.createRadialGradient(pointX, pointY, 0, pointX, pointY, 50);
            grd.addColorStop(0, "rgba(255,255,255,0.6)"); 
            grd.addColorStop(1, "transparent"); 
            ctx.fillStyle = grd;
            ctx.beginPath();
            ctx.arc(pointX,pointY,50,0,Math.PI*2,true);
            ctx.fill();
            ctx.closePath();
        }

        canvas.addEventListener('touchstart',function(e){
            drawPoint(e.touches[0].screenX,e.touches[0].screenY);
        },false);

        canvas.addEventListener('touchmove',function(e){
            e.preventDefault();
            drawPoint(e.touches[0].screenX,e.touches[0].screenY);
        },false);

        canvas.addEventListener('mousemove',function(e){
            e.preventDefault();
            drawPoint(e.clientX,e.clientY);
        },false);
    }

    </script>
</head>
<body onLoad="javascript:init();">
<div>
    <p>testing... testing... testing... testing... testing... testing... testing... testing... testing... testing... testing... testing... testing... testing... testing... testing... testing... testing... testing... </p>
    <canvas id="c" width="400" height="400"></canvas>
</div>
</body>

1 个答案:

答案 0 :(得分:2)

Rough method :检查画布的imageData

var imageData = ctx.getImageData(0, 0, ctx.canvas.width, ctx.canvas.height);
var trans = 0;
for (var i = 0; i < imageData.data.length; i += 4) {
  if (imageData.data[3 + i] === 0) {
    trans++
  }
}
var percent = trans / (imageData.data.length / 4) * 100;

但是不要在setInterval中执行它,getImageData很慢并且内存耗尽!

至少,仅在throttled mousemove event中进行。

更好的方法是these comments,但我还没有时间写它..
如果有人想这样做,我很乐意使用它; - )