Reputation: 283
I am creating a color picker using javascript and the HTML5 canvas. I'm attempting to use the following code to get the color of a specific pixel on the color picker, but it just returns black every time: rgb(0, 0, 0)
. However, if I replace this.getGradientPos.X
and this.getGradientPos.Y
with hard-coded values, it works fine. It also works if only one of the X
or Y
variables is in place and the other is hard-coded. In the console, curGradPos.X
and curGradPos.Y
both show correct positions. I'm at a loss as to what could be wrong.
ColorPicker.prototype.getGradientColor =
function()
{
j = this.context.getImageData(this.curGradPos.X, this.curGradPos.Y, 1, 1);
k = j.data;
console.log(this.curGradPos);
console.log(k);
return {r: k[0], g: k[1], b: k[2]};
}
This initializes the variables.
function ColorPicker()
{
this.canvas = document.getElementById('colorPicker');
this.curColor = this.baseColor = {r: 255, g: 0, b: 0};
this.context = this.canvas.getContext('2d');
this.curGradPos = {X: 255, Y: 255};
}
And this updates the curGradPos variable on mousemove.
rect = this.canvas.getBoundingClientRect();
x = event.clientX - rect.left;
y = event.clientY - rect.top;
if (x >= 15 && x < 15+255 && y >= 15 && y < 15+255)
{
this.curGradPos = {X: x, Y: y}; //seems to be correct
this.drawColorGradient();
this.curColor = this.getGradientColor(); //above function with issue
}
Upvotes: 2
Views: 994
Reputation:
The code seem to read the color from the marker rather than the color "behind" it.
The color needs to be read from the position and then set the marker or you will get the color of the marker instead in that position; and of course as the marker is black that color will be returned each time.
Upvotes: 1