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
I hope this helps. So… you need to use
save
andrestore
methods.Here is the working example and here is more info about save and reset methods.
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 insecond
.