3

我需要在画布中选择一种特定颜色并获取该颜色的 RGB 值。谁能帮我做到这一点?

这是画布的代码

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");
4

1 回答 1

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];
});
于 2013-07-03T10:01:58.927 回答