This question already has an answer here:
html 5 canvas LineTo() line color issues

(1个答案)


在10个月前关闭。




问题是笔触的不透明度低于填充的不透明度,并且我无法使笔触的颜色与填充的颜色具有相同的不透明度。

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.strokeStyle = "rgba(255,0,0,1)";
ctx.fillStyle = "rgba(255,0,0,1)";
ctx.strokeRect(20, 20, 25, 25);
ctx.fillRect(20, 50, 25, 25);
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
    Your browser does not support the HTML5 canvas tag.</canvas>


如果将fillStyle的不透明度设置为0.5,则它们将是相同的,但是我们不能提高笔触的不透明度。

那么如何设置笔触颜色与填充颜色相同呢?

最佳答案

它们具有完全相同的颜色。问题是抗锯齿。

如果将笔划加宽,可以检查一下笔划看起来是否较黑。

ctx.lineWidth = 5;

它在笔触的中央部分将显示为强烈的红色,而在边缘将显示为非饱和的红色。

可悲的是,您可以控制它(即将其关闭),因为它取决于浏览器。

您可以在其他question中阅读有关它的更多信息(并寻找替代方法)。

对我来说更好的技巧是将 Canvas 平移半像素距离。
ctx.translate(0.5, 0.5);

建议使用herehere。我不能确定是否会在每种浏览器中达到预期的效果(我在Firefox上进行了测试)。

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.strokeStyle = "rgba(255,0,0,1)";
ctx.fillStyle = "rgba(255,0,0,1)";
ctx.translate(0.5, 0.5);
ctx.strokeRect(20, 20, 25, 25);
ctx.fillRect(20, 50, 25, 25);
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">Your browser does not support the HTML5 canvas tag.</canvas>

09-06 05:20