是否可以查询HTML Canvas对象以获取特定位置的颜色?
W3C文档中有关于像素操作的部分.
这是一个如何反转图像的示例:
var context = document.getElementById('myCanvas').getContext('2d'); // Get the CanvasPixelArray from the given coordinates and dimensions. var imgd = context.getImageData(x, y, width, height); var pix = imgd.data; // Loop over each pixel and invert the color. for (var i = 0, n = pix.length; i < n; i += 4) { pix[i ] = 255 - pix[i ]; // red pix[i+1] = 255 - pix[i+1]; // green pix[i+2] = 255 - pix[i+2]; // blue // i+3 is alpha (the fourth element) } // Draw the ImageData at the given (x,y) coordinates. context.putImageData(imgd, x, y);
你试过getImageData方法吗?
var data = context.getImageData(x, y, 1, 1).data; var rgb = [ data[0], data[1], data[2] ];
是的,只要你有它的背景.如何获取画布上下文?
var imgData = context.getImageData(0,0,canvas.width,canvas.height); // { data: [r,g,b,a,r,g,b,a,r,g,..], ... } function getPixel(imgData, index) { var i = index*4, d = imgData.data; return [d[i],d[i+1],d[i+2],d[i+3]] // returns array [R,G,B,A] } // AND/OR function getPixelXY(imgData, x, y) { return getPixel(imgData, y*imgData.width+x); }
是的,请查看getImageData().以下是使用canvas破解验证码的示例:
http://ejohn.org/blog/ocr-and-neural-nets-in-javascript/
function GetPixel(x, y) { var p = ctx.getImageData(x, y, 1, 1).data; var hex = "#" + ("000000" + rgbToHex(p[0], p[1], p[2])).slice(-6); return hex; } function rgbToHex(r, g, b) { if (r > 255 || g > 255 || b > 255) throw "Invalid color component"; return ((r << 16) | (g << 8) | b).toString(16); }
请注意,getImageData返回一个快照.意义是:
更改将在后续的putImageData中生效
getImageData和putImageData调用相对较慢