我需要在画布中选择特定颜色并获取该颜色的RGB值。 有人可以帮我这么做吗?
以下是canvas
的代码var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var grd=ctx.createLinearGradient(0,0,200,0);
grd.addColorStop(0,"red");
grd.addColorStop(0.15,"yellow");
grd.addColorStop(0.3,"green");
grd.addColorStop(0.45,"aqua");
grd.addColorStop(0.6,"blue");
grd.addColorStop(0.7,"fuchsia");
grd.addColorStop(1,"red");
答案 0 :(得分:1)
使用jQuery:
// utility function to retrieve click position inside the canvas
function findPos(obj) {
var curleft = 0, curtop = 0;
if (obj.offsetParent) {
do {
curleft += obj.offsetLeft;
curtop += obj.offsetTop;
} while (obj = obj.offsetParent);
return { x: curleft, y: curtop };
}
return undefined;
}
$('#myCanvas').click(function(e) {
var pos = findPos(this);
var x = e.pageX - pos.x;
var y = e.pageY - pos.y;
var coord = "x=" + x + ", y=" + y;
var c = this.getContext('2d');
var p = c.getImageData(x, y, 1, 1).data; // get 1x1 pixels area at the (x,y) position
var red_value = p[0];
var green_value = p[1];
var blue_value = p[2];
});