我尝试从 Canvas 背景图像中获取所选像素的颜色,但是我所得到的(作为颜色)是0000。
你能帮助我吗?我的错误在哪里?
我的代码(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]);
}
最佳答案
我编写了脚本的新版本,现在可以正常工作了。
我误解了getImageData参数。
这是新版本:
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]);
});
关于javascript - html5:canvas.getImageData无法正常工作-为什么?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6869989/