Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading the RGB value of a canvas pixel

I have put an image in canvas and I want to get the RGB value of the pixels of that image when the user moves the mouse over the image. Here is the code which I have written:

<canvas id="myCanvas" width="200" height="200" style="border: red;border-style: dotted">
Your browser does not support the canvas element.
</canvas>
<script>
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");

var destX = 0;
var destY = 0;

var imageObj = new Image();
imageObj.onload = function()
{
context.drawImage(imageObj, destX, destY);
};
imageObj.src = "zain.jpg";

canvas.onclick = function(e) {
    var x = e.pageX;
    var y = e.pageY;
    var canvasColor = context.getImageData(x, y, 1,1); // rgba e [0,255]
    var pixels = canvasColor.data;
    var r = pixels[0];
    var g = pixels[1];
    var b = pixels[2];
    document.body.style.backgroundColor = "rgb("+r+','+g+','+b+")";
}
like image 340
Zain Avatar asked Sep 10 '11 18:09

Zain


2 Answers

Try something along this:

var color = document.getElementById("color");
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");

var imageObj = new Image();
imageObj.onload = function(){
    context.drawImage(imageObj, destX, destY);
};
imageObj.src = "zain.jpg";

canvas.onmousemove = function(e) {
    // not so sure about these... might need to offset them or so
    var x = e.x;
    var y = e.y;

    // set color now
    var canvasColor = context.getImageData(x, y, 1, 1).data; // rgba e [0,255]
    var r = canvasColor[0];
    var g = canvasColor[1];
    var b = canvasColor[2];

    color.style.backgroundColor = 'rgb(' + r + ',' + g + ',' + b + ')';
}

Note that the snippet expects you have a div with id "color" somewhere. It sets the pixel color there.

like image 192
Juho Vepsäläinen Avatar answered Oct 10 '22 08:10

Juho Vepsäläinen


What you're looking for here is the getImageData() call.

So, your solution would look something like this:

function getColor(canvas, x, y) {    
    var context = canvas.getContext("2d");
    var pixel = context.getImageData(x, y, 1, 1);

    // Red = rgb[0], green = rgb[1], blue = rgb[2]
    // All colors are within range [0, 255]
    var rgb = pixel.data;

    return rgb;
}

function canvasMouseMove(e) {
    var x = e.layerX, y = e.layerY;
    var rgb = getColor(canvas, x, y);
    var rgb_string = "rgb(" + rgb[0] + "," + rgb[1] + "," + rgb[2] + ")";

    document.body.style.backgroundColor = rgb_string;
}

canvas.onmousemove = canvasMouseMove;

As @bebraw pointed out, you may need to handle the mouse location differently depending on the browser being used. For that, you might consider using jQuery or another JS library for simplicity.

like image 29
Xenethyl Avatar answered Oct 10 '22 09:10

Xenethyl