Get Colour from the Image - HTML5 Canavs
This code display a way to get colour from the image. HTML5 canvas method helps in retrieving image pixel profile. Check attuts.com for more details on getting color from the static image.
by abdul quadir
HTML
<div class="container">
<img src="http://www.attuts.com/wp-content/uploads/2015/01/attus.jpg" alt="source: fashionara.com" width="500" height="494" 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:500px;
}
.container {
position:relative;
width:500px;
height:494px;
}
#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.
var imgObj;
var canvasObj;
var toggleButton = false // toggling bottom button action
$("#btn").click(
function (e) {
if (!toggleButton) {
imgObj = document.getElementById('imgEle');
toggleButton = true;
$(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, 1, 1).data;
var Rv = rgbdata[0];
var Gv = rgbdata[1];
var Bv = rgbdata[2];
alert("R Value is "+ Rv + " Green Value is " +Gv+ " Blue value is "+Bv);
});
} 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
$(canvasObj).off('click');
$(canvasObj).remove();
$("#btn").text('Edit Me');
$("#tag").text("Image");
}
});