简体   繁体   中英

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]);

}

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]);
});

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM