[with solution]: Problem with context.save () and context.restore ()
tmarti opened this issue · 4 comments
The problem
The jest-canvas-mock/CanvasRenderingContext2D
class save
and restore
operations should behave in the same way as browser/CanvasRenderingContext2D
but it doesn't.
If we execute the following code:
function _do (cont) {
var tmp = [];
cont.scale(0.5, 0.5);
cont.save ();
tmp.push (cont.getTransform ().m11);
cont.scale (0.5, 0.5);
tmp.push (cont.getTransform ().m11);
cont.restore ();
tmp.push (cont.getTransform ().m11);
console.log (tmp);
}
var the_canvas = some real canvas;
console.log ("save/restore sequence for browser/CanvasRenderingContext2D")
_do (
the_canvas.getContext('2d')
);
console.log ("save/restore sequence for jest-canvas-mock/CanvasRenderingContext2D")
_do (
new CanvasRenderingContext2D (
the_canvas
)
);
We get the following output:
save/restore sequence for browser/CanvasRenderingContext2D
Array(3) [ 0.5, 0.25, 0.5 ]
save/restore sequence for jest-canvas-mock/CanvasRenderingContext2D
Array(3) [ 0.5, 0.25, 0.25 ]
Expected behaviour
The output for jest-canvas-mock/CanvasRenderingContext2D
should be the same as browser/CanvasRenderingContext2D
...
Array(3) [ 0.5, 0.25, 0.5 ]
... instead of...
Array(3) [ 0.5, 0.25, 0.25 ]
(notice the 0.25
intead of 0.5
as last element in the array)
The solution
There we go!
The line...
... needs to be changed to...
this._transformStack.push(this._transformStack[this._stackIndex].slice ());
(notice the .slice()
)
@tmarti Thank you so much for this catch. This is a really easy fix, and you can submit a pull request if you'd like.
@tmarti Mock canvas when run unit test cases with jest. For more browser environment, you can use
jest-electron for real browser runtime.
I'm going to take care of this in a few days. Sorry for the wait.