如何用javascript擦除部分图像,擦除像素的结果是透明的?

时间:2013-08-04 10:53:21

标签: javascript html5-canvas

我的要求是用户上传图片,然后用户可以删除他们不想要的图像像素,例如他们有人的形象,他们不想要人体的像素然后他们可以擦除它。我的程序是一个Web基础。我使用js画布,但我只能通过添加白色像素来擦除,无论如何我想要白色像素是transperent。我该怎么办?

1 个答案:

答案 0 :(得分:1)

您可以使用合成来“擦除”以前绘制的图像。

enter image description here

Context.globalCompositeOperation =“destination-out”的行为如下:

任何与上一个图形重叠的后续图形将导致上一个图形被“擦除”。

        ctx.drawImage(img,0,0);

        ctx.globalCompositeOperation="destination-out";
        ctx.beginPath();
        ctx.moveTo(0,0);
        ctx.lineTo(300,300);
        ctx.moveTo(300,0);
        ctx.lineTo(0,300);
        ctx.lineWidth=20;
        ctx.fillStyle="blue";
        ctx.stroke();

这是代码和小提琴:http://jsfiddle.net/m1erickson/puYTy/

<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>

<style>
    body{ background-color: ivory; padding:20px; }
    #canvas{border:1px solid red;}
</style>

<script>
$(function(){

    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");


    var img=new Image();
    img.onload=function(){
        start();
    }
    img.src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house-icon.png";


    function start(){

        ctx.drawImage(img,0,0);

        ctx.globalCompositeOperation="destination-out";
        ctx.beginPath();
        ctx.moveTo(0,0);
        ctx.lineTo(300,300);
        ctx.moveTo(300,0);
        ctx.lineTo(0,300);
        ctx.lineWidth=20;
        ctx.fillStyle="blue";
        ctx.stroke();
    }



}); // end $(function(){});
</script>

</head>

<body>
    <p>Composite: destination-out</p>
    <p>The lines will "erase" the existing image</p>
    <canvas id="canvas" width=300 height=300></canvas>
</body>
</html>