I am looking for a jquery image eraser plugin that can erase parts of an actual image. For example, if a user uploads an image of a monkey and decides that he does not want the tail, then he should be able to move the mouse over the tail and erase it. To keep it simple, lets assume that all images are black and white and background is always white.
I have searched for quite some time and most "jquery eraser" plugins point to a canvas eraser and not a true image eraser. For example: http://minimal.be/lab/jQuery.eraser/ this creates a canvas on top of an image and you can then erase the canvas - this is NOT the requirement
Couple of other threads on stackoverflow are interesting: like How to erase partially image with javascript and result of erase pixel is transperent?
Is there a plugin that can do this with canvas
I don't know of a non-canvas plugin that does just image erasing.
I don't think its easily done on the client-side without the canvas element because html5 canvas is the only native element that can edit an existing image at the pixel level and then save the edited image.
As you've discovered, it's easy enough to do using html5 canvas:
drawImage
an image onto a canvas element, destination-out
compositing to let the user erase part of the image,.toDataURL
Here's a simple proof-of-concept for you to start from:
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
function reOffset(){
var BB=canvas.getBoundingClientRect();
offsetX=BB.left;
offsetY=BB.top;
}
var offsetX,offsetY;
reOffset();
window.onscroll=function(e){ reOffset(); }
window.onresize=function(e){ reOffset(); }
var img=new Image();
img.crossOrigin='anonymous';
img.onload=start;
img.src="https://dl.dropboxusercontent.com/u/139992952/multple/monkey.jpg";
function start(){
canvas.width=img.width;
canvas.height=img.height;
ctx.drawImage(img,0,0);
ctx.globalCompositeOperation='destination-out';
$("#canvas").mousedown(function(e){handleMouseDown(e);});
$("#save").click(function(){
alert('This save-to-image operation is prevented in Stackoverflows Snippet demos but it works when using an html file.');
var html="<p>Right-click on image below and Save-Picture-As</p>";
html+="<img src='"+canvas.toDataURL()+"' alt='from canvas'/>";
var tab=window.open();
tab.document.write(html);
});
}
function handleMouseDown(e){
// tell the browser we're handling this event
e.preventDefault();
e.stopPropagation();
var x=parseInt(e.clientX-offsetX);
var y=parseInt(e.clientY-offsetY);
ctx.beginPath();
ctx.arc(x,y,15,0,Math.PI*2);
ctx.fill();
}
body{ background-color: white; }
#canvas{border:1px solid red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<h4>Click on image to erase 10 pixels around mouse</h4>
<canvas id="canvas" width=300 height=300></canvas>
<br>
<button id='save'>Save edited canvas as an image</button>