Florent
Florent

Reputation: 446

Why color changes after redrawing again on canvas using javascript?

Here a sample of code that product the effect on color.

The question is "why rectangles (rect 1 and rect 2) are not the same color ?

    <!DOCTYPE html>
    <html>
    <body>
    <canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
    Your browser does not support the HTML5 canvas tag.</canvas>

    <script>
    var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");

    ctx.strokeRect(5, 5, 25, 15); //rect 1

    ctx.strokeRect(55, 5, 25, 15); // rect 2
    ctx.strokeRect(55, 5, 25, 15); // rect 2 again
    </script> 
    </body>
    </html>

Upvotes: 0

Views: 97

Answers (2)

Sever van Snugg
Sever van Snugg

Reputation: 713

The problem here is the line width. If you change it to 2, you get the same rectangles, but without the opacity.

ctx.lineWidth = 2;

ctx.strokeRect(5, 5, 24, 14); //rect 1
ctx.strokeRect(55, 5, 24, 14); // rect 2
ctx.strokeRect(55, 5, 24, 14); // rect 2 again

I assume that for some reason, the browser uses a stroke that is below 1 pixel at the point on the line and to compensate for that, it reduces the opacity of the stroke.

Example with line width of 2: https://jsfiddle.net/2buo5cfw/4/

Upvotes: 2

Alireza
Alireza

Reputation: 1764

because you are drawing two rectangles in the same place and that make the color of canvas that way.

Test this one.

    <!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>

<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");

ctx.strokeRect(5, 5, 25, 15); //rect 1

ctx.strokeRect(55, 5, 25, 15); // rect 2
ctx.strokeRect(75, 5, 25, 15); // rect 2 again
</script> 
</body>
</html>

Upvotes: 1

Related Questions