Remove and Get Pixel from the Image - HTML5 Canvas
Remove Image pixel from the image on click. Try Edit Me button and click on Canvas.
HTML
<div class="container">
<img src="http://www.attuts.com/wp-content/uploads/2015/01/attus.jpg" alt="source: fashionara.com" width="555" height="555" id="imgEle" />
<div id="tag">Image</div>
</div>
<div>
<button id="btn">Edit Me</button>
</div>
CSS
#btn {
height:40px;
color:white;
background:green;
width:555px;
}
.container {
position:relative;
width:555px;
height:555px;
background: #00ff00 url("http://www.getpaint.net/doc/latest/images/layerswindow/checkerboard.png");
}
#tag {
position:absolute;
right:0px;
top:20px;
background:black;
color:white;
padding:10px;
min-width:80px;
text-align:center;
}
JavaScript
// get Full tutorial on attuts.com - how to remove and get color from the image.
//Click on Bottom Edit Me Button to make it work.
var imgObj;
var canvasObj;
var threshold = 10;
var toggleButton = false // toggling bottom button action
$("#btn").click(
function (e) {
if (!toggleButton) {
imgObj = document.getElementById('imgEle');
toggleButton = false;
$(imgObj).remove();
$(".container").append($("<canvas id='canEle' width='500' height='494'></canvas>"));
canvasObj = document.getElementById("canEle");
var ctx = canvasObj.getContext("2d");
ctx.drawImage(imgObj, 0, 0); // drawing image into canvas
$("#btn").text('finish Editing');
$("#tag").text("Canvas");
$(canvasObj).on('click',function(event){
var x = event.pageX - this.offsetLeft;
var y = event.pageY - this.offsetTop;
var rgbdata = ctx.getImageData(x, y,5, 555).data;
var Rv = rgbdata[0];
var Gv = rgbdata[1];
var Bv = rgbdata[2];
// get the image data object
var image = ctx.getImageData(0, 0, 555, 555);
// get the image data values
var imageData = image.data,
length = imageData.length;
// set every fourth value to 50
var r=0, g=1, b=2,a=3;
for(var i=0; i < length; i+=4){
if (
imageData[i+r] >= Rv-threshold && imageData[i+r]<Rv+threshold &&
imageData[i+g] >= Gv-threshold && imageData[i+g]<Gv+threshold &&
imageData[i+b] >= Bv-threshold && imageData[i+b]< Bv+threshold ) // if white then change alpha to 0
{imageData[i+a] = 0;}
}
// after the manipulation, reset the data
image.data = imageData;
// and put the imagedata back to the canvas
ctx.putImageData(image, 0, 0);
});
} else {
toggleButton = false;
$(".container").append($('<img width="500" height="494" id="imgEle" />'));
document.getElementById("imgEle").src = canvasObj.toDataURL('image/png'); // transfer canvas data to img
...