skip to Main Content

I am curious on the curious behaviour of js, in particular with this method .strokeStyle which usually is used to change the color of a stroke on a HTML canvas. It seems to me quite peculiar, for exmaple if I use 2 functions such as in this snippet (to draw an ‘L’)-

<!DOCTYPE html>
<html>
<body>
<h1>HTML5 Canvas</h1>
<h2>The stroke() Method</h2>

<canvas id="myCanvas" width="300" height="150" style="border:1px solid grey"></canvas>

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

function first() {
ctx.beginPath();
ctx.strokeStyle = "red";
ctx.moveTo(20, 20);
ctx.lineTo(20, 100);
ctx.stroke();
};

function second() {
ctx.beginPath();
ctx.moveTo(20, 100);
ctx.lineTo(70, 100);
ctx.stroke();
};

first();
second();
</script> 

</body>
</html>

One might expect that when the second() is executed, it’s stroke color will be Black (since this is the default). However, this does not happen and the stroke color is Red. This seems strange to me since coming from the land of functional programming, I see function as isolated, independent units of code. Am I doing something wrong? if not, then is there a way to contain it’s global effects?

2

Answers


  1. I hope this helps. So… you need to use save and restore methods.

    const c = document.getElementById("myCanvas");
    const ctx = c.getContext("2d");
    function first() {
      ctx.save(); // Save the current state
      ctx.beginPath();
      ctx.strokeStyle = "red";
      ctx.moveTo(20, 20);
      ctx.lineTo(20, 100);
      ctx.stroke();
      ctx.restore(); // Restore the previous state
    }
    
    function second() {
      ctx.save(); // Save the current state
      ctx.beginPath();
      ctx.strokeStyle = "black"; // Explicitly set the stroke style to black
      ctx.moveTo(20, 100);
      ctx.lineTo(70, 100);
      ctx.stroke();
      ctx.restore(); // Restore the previous state
    }
    
    first();
    second();
    

    Here is the working example and here is more info about save and reset methods.

    Login or Signup to reply.
  2. The canvas context acts like a JS object (with lots of getter setter magics, but here it doesn’t matter). Just like if you modified a plain object in first, its state would expose the modifications in second.

    const ctx = { strokeStyle: "black" } // plain object
    
    function first() {
      ctx.strokeStyle = "red";
      console.log("in first", ctx.strokeStyle);
    };
    
    function second() {
      console.log("in second", ctx.strokeStyle);
    };
    
    first();
    second();
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search