Newbie
Newbie

Reputation: 1714

html5: canvas.getImageData not working correctly - Why?

I try to get the color of the selected pixel from my canvas background-image, but all i get (as color) is 0000. Can you help me? Where is my error?

My Code (js):

var canvas;
var mouse_position = [];
var color;

$(document).ready(function(){
    canvas_element = $('<canvas></canvas>');
    canvas = canvas_element.get(0).getContext("2d");
    canvas_element.appendTo('body');
    init_canvas();  
});

function init_canvas(){
    var img = new Image();
    img.src = 'static/img/albatros.jpg';
    img.width = 600;
    img.height = 800;
    canvas.drawImage(img, 0, 0);

    $(document).mousemove(function(e){
        if(e.offsetX){
            mouse_position.x = e.offsetX;
            mouse_position.y = e.offsetY;
        }else if(e.layerY){
            mouse_position.x = e.layerX;
            mouse_position.y = e.layerY;
        }

        show_color();

    });
}


function show_color(){
    color  = canvas.getImageData(mouse_position.x,mouse_position.y,1,1).data;
    console.info("red: " + color[0] + " green: " + color[1] + " blue: " + color[2] + "alpha: " +color[3]);

}

Upvotes: 3

Views: 8898

Answers (2)

user4200808
user4200808

Reputation:

I knew it's an old question, just got the same problem, but you can do it like this:

//Get the mouse position IN canvas
rect = canvas_element.getBoundingClientRect(),
   x = e.clientX - rect.left,
   y = e.clientY - rect.top

//Get the data of the 1x1 px
imageData = canvas.getImageData(x, y, 1, 1).data;

The function getImageData() gets the data by your position in canvas, not the whole page.

Upvotes: 0

Newbie
Newbie

Reputation: 1714

I wrote a new version of my script and now, it is working. I misunderstood the getImageData params. Here is the new version:

var path = 'static/img/albatros.jpg',
color = new Array();
img = new Image();
img.src=path;
canvas = document.createElement('canvas');
canvas.id = 'canvas';
canvas.width = img.width;
canvas.height = img.height;
ccontext = null;

$(document).ready(function(){
    $('body').prepend(canvas);
    init_canvas();
});

function init_canvas(){
    ccontext = canvas.getContext("2d");
    ccontext.drawImage(img, 0, 0);
    imgData = ccontext.getImageData(0, 0, $('#canvas').width(),  $('#canvas').height());
    for(i = imgData.data.length; i--;){
        color[i] = imgData.data[i];
    }
}

$('#canvas').live('mousemove', function (e) {
   var offset = $('#canvas').offset();
    var eX = e.pageX - this.offsetLeft;
    var eY = e.pageY - this.offsetTop;
    var z = eY * this.width * 4;
    var s = eX * 4;
    console.info("red: " + imgData.data[z+s] + " green: " + imgData.data[z+s+1] + " blue: "+ imgData.data[z+s+2] + ' alpha: ' +imgData.data[z+s+3]);
});

Upvotes: 2

Related Questions