cavaliercyber
cavaliercyber

Reputation: 234

How to erase partially image with javascript and result of erase pixel is transperent?

My requirement is user upload image then user can erase some pixel of image that they don't want it e.g. They have image of human and they don't want pixel of human body then they can erase its. My program is a web base. I use js canvas but I can only erase by adding white pixel to image anyway I want white pixel is transperent. How I suppose to do?

Upvotes: 0

Views: 1048

Answers (1)

markE
markE

Reputation: 105015

You can use compositing to “erase” a previously drawn image.

enter image description here

Context.globalCompositeOperation=”destination-out” behaves like this:

Any subsequent drawing that overlaps the previous drawing will cause the previous drawing to be “erased”.

        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();

Here’s code and a Fiddle: 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>

Upvotes: 1

Related Questions