Reputation: 167
I am wanting to create a canvas scene that involves drawing lines. Literally, to give the appearance of solid lines being drawn from one x/y coordinate to anther x/y coordinate. My trouble seems to be with my use of save() and restore(). The way I understand it is, if I save() my canvas before I begin drawing, I can then call on restore() to reset my canvas back to that beginning state. In this way, I can begin my next line without a distorted canvas.
When the code below is run, the first line is drawn as intended. I then call restore() to allow me to work with a non-distorted canvas for the next line. As a result (so it seems) the second line is drawn as instructed. I again call on restore() to allow me to draw the third line from one specified set of coordinates to another. However, this third line is not starting at the coordinates given. It’s as if the canvas is still distorted from the previous line, but I can’t understand as to why. Can anyone shed some light on my dilemma? (Also, it there is an easier to way to create line drawings of this style, for the web, could you let me know?)
var canvas = document.getElementById('canvas');
var c = canvas.getContext('2d');
c.save();
var a = 0;
function callVerticalTeal() {
if(a < 200) { //draw line the length of 200px
drawVerticalTeal();
a++;
setTimeout(callVerticalTeal, 0);
}
setTimeout(callHorizontalRed, 1200);
}
function drawVerticalTeal(){
c.transform(1,0,0,1,0,1);
c.beginPath();
c.moveTo(325, 200);
c.strokeStyle = 'teal';
c.lineCap = 'round';
c.lineWidth = 10;
c.lineTo(325, 200);
c.stroke();
}
// Start the loop
setTimeout(callVerticalTeal, 0);
var b = 0;
function callHorizontalRed() {
if(b < 200) {
drawHorizontalRed();
b++;
setTimeout(callHorizontalRed, 1000);
}
c.restore();
setTimeout(callHorizontalBlack, 1200);
}
function drawHorizontalRed(){
c.restore();
c.transform(1,0,0,1,1,0);
c.beginPath();
c.moveTo(325, 200);
c.strokeStyle = 'brown';
c.lineCap = 'round';
c.lineWidth = 10;
c.lineTo(325, 200);
c.stroke();
}
var x = 0;
function callHorizontalBlack() {
if(x < 200) {
draw();
x++;
setTimeout(call, 5000);
}
setTimeout(callVerticalBlack, 1200);
}
function draw(){
c.restore();
c.transform(1,0,0,1,1,0);
c.beginPath();
c.moveTo(325, 400);
c.strokeStyle = 'black';
c.lineCap = 'round';
c.lineWidth = 10;
c.lineTo(325, 400);
c.stroke();
}
Upvotes: 0
Views: 456
Reputation: 370
You call context.save() only once. Typically context.save() is called first in any drawing method, and context.restore() is the last call. So it is an interceptor, if you want to call it so.
function paintSomething() {
ctx.save();
// now paint something
ctx.restore(); // we now are clean again, because we have the previously saved state
}
Upvotes: 1