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?
我试图从我的画布背景图像中获取所选像素的颜色,但我得到的(作为颜色)是0000.你能帮助我吗?我的错误在哪里?
My Code (js):
我的代码(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]);
}
2
I wrote a new version of my script and now, it is working. I misunderstood the getImageData params. Here is the new version:
我写了一个新版本的脚本,现在它正在运行。我误解了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]);
});
0
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.
函数getImageData()通过画布中的位置获取数据,而不是整个页面。
本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.silva-art.net/blog/2011/07/29/7fb1c026d91e6a7a498d8759b4aa94c3.html。