Javascript canvas 线性渐变不会变成全彩
Javascript canvas linear gradient not going to full color
我目前正在为我正在制作的网站编写颜色选择器,并且
线性渐变似乎不会变成全白。
我正在使用 canvas 来获取 RGB 颜色数据。
参见 this screenshot
如您所见,我得到的最大值为 254。
我使用以下函数将渐变绘制到 canvas.
draw_color_square(hue){
var gradB = this.ctx.createLinearGradient(0, 0, 0, 255);
gradB.addColorStop(0, "white");
gradB.addColorStop(1, "black");
var gradC = this.ctx.createLinearGradient(0,0,255,0);
gradC.addColorStop(0, "hsla(" + hue + ",100%,50%,0)");
gradC.addColorStop(1, "hsla(" + hue + ",100%,50%,1)");
this.ctx.fillStyle = gradB;
this.ctx.fillRect(0, 0, 255, 255);
this.ctx.fillStyle = gradC;
this.ctx.globalCompositeOperation = "multiply";
this.ctx.fillRect(0, 0, 255, 255);
this.ctx.globalCompositeOperation = "source-over";
}
我已检查滑块是否移动到位置 [0, 0]
几乎所有内容都移动了 1 个像素。 canvas 的宽度必须是 256 像素,而您已将其设置为 255 像素。你的 fillrect 只填充 255 像素宽度,你的渐变从像素 0(据我所知不存在)开始到像素 255。我已经更新了所有内容以使其按预期工作。
最重要的部分是这个:
draw_color_square(hue){
var gradB = this.ctx.createLinearGradient(1, 1, 1, 256);
gradB.addColorStop(0, "white");
gradB.addColorStop(1, "black");
var gradC = this.ctx.createLinearGradient(1,1,256,1);
gradC.addColorStop(0, "hsla(" + hue + ",100%,50%,0)");
gradC.addColorStop(1, "hsla(" + hue + ",100%,50%,1)");
this.ctx.fillStyle = gradB;
this.ctx.fillRect(0, 0, 256, 256);
this.ctx.fillStyle = gradC;
this.ctx.globalCompositeOperation = "multiply";
this.ctx.fillRect(0, 0, 256, 256);
this.ctx.globalCompositeOperation = "source-over";
}
这里是fiddle:https://jsfiddle.net/r1ka8ejx/45/
我目前正在为我正在制作的网站编写颜色选择器,并且 线性渐变似乎不会变成全白。 我正在使用 canvas 来获取 RGB 颜色数据。 参见 this screenshot
如您所见,我得到的最大值为 254。 我使用以下函数将渐变绘制到 canvas.
draw_color_square(hue){
var gradB = this.ctx.createLinearGradient(0, 0, 0, 255);
gradB.addColorStop(0, "white");
gradB.addColorStop(1, "black");
var gradC = this.ctx.createLinearGradient(0,0,255,0);
gradC.addColorStop(0, "hsla(" + hue + ",100%,50%,0)");
gradC.addColorStop(1, "hsla(" + hue + ",100%,50%,1)");
this.ctx.fillStyle = gradB;
this.ctx.fillRect(0, 0, 255, 255);
this.ctx.fillStyle = gradC;
this.ctx.globalCompositeOperation = "multiply";
this.ctx.fillRect(0, 0, 255, 255);
this.ctx.globalCompositeOperation = "source-over";
}
我已检查滑块是否移动到位置 [0, 0]
几乎所有内容都移动了 1 个像素。 canvas 的宽度必须是 256 像素,而您已将其设置为 255 像素。你的 fillrect 只填充 255 像素宽度,你的渐变从像素 0(据我所知不存在)开始到像素 255。我已经更新了所有内容以使其按预期工作。
最重要的部分是这个:
draw_color_square(hue){
var gradB = this.ctx.createLinearGradient(1, 1, 1, 256);
gradB.addColorStop(0, "white");
gradB.addColorStop(1, "black");
var gradC = this.ctx.createLinearGradient(1,1,256,1);
gradC.addColorStop(0, "hsla(" + hue + ",100%,50%,0)");
gradC.addColorStop(1, "hsla(" + hue + ",100%,50%,1)");
this.ctx.fillStyle = gradB;
this.ctx.fillRect(0, 0, 256, 256);
this.ctx.fillStyle = gradC;
this.ctx.globalCompositeOperation = "multiply";
this.ctx.fillRect(0, 0, 256, 256);
this.ctx.globalCompositeOperation = "source-over";
}
这里是fiddle:https://jsfiddle.net/r1ka8ejx/45/