javascripthtmlcanvashtml5-canvas

Is .strokeStyle of the canvas API a method which makes itself global?


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')-

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();
<h1>HTML5 Canvas</h1>
<h2>The stroke() Method</h2>
<canvas id="myCanvas" width="300" height="150" style="border:1px solid grey">
</canvas>

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?


Solution

  • 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();