4

Problem is that stroke opacity is lower than fill opacity and I can't get stroke color to be the same opacity as fill color.

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>

If we set fillStyle opacity 0.5, than they will be the same, but we can't raise opacity of stroke.

So how set stroke color to be the same as fill color?

evolutionxbox
  • 3,932
  • 6
  • 34
  • 51

1 Answers1

5

They have exactly the same color. The problem is the antialiasing.

You can check that the stroke looks darker if you make it wider.

ctx.lineWidth = 5;

It will have an intense red in the central part of the stroke but a non-saturated one in the edges.

Sadly, you can control it (i.e. turn it off) because it depends on the browser.

You can read more about it (and look for alternatives) in this other question.

The trick that was working better for me is to translate the canvas by half-pixel distance.

ctx.translate(0.5, 0.5);

It was suggested here and here. I can not be sure if is going to achieve the desired effect in every browser though (i tested it on 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>
David
  • 6,695
  • 3
  • 29
  • 46
  • 1
    Another workaround would be to draw four mini rectangles around the main rectangle, mimicking the lines. – E. Zacarias Jan 30 '20 at 11:56
  • 1
    @E.Zacarias - True. I also read it in this other [answer](https://stackoverflow.com/a/41557540/5247200). The problem I see is that it won't work is the desired opacity is lower than 1. – David Jan 30 '20 at 11:59
  • Thank you for clearing that up for me, it's pretty much solves my problem – tra1lblaz3r Jan 30 '20 at 12:02