How can I get the path2D after the canvas has done its calculations?
ctx.resetTransform()
ctx.translate(2, 2)
ctx.scale(2, 2)
ctx.beginPath()
ctx.moveTo(30, 50)
ctx.lineTo(150, 100)
ctx.strokeStyle = 'red'
ctx.stroke()
ctx.closePath()
//get path2D
You can't. The context's current default path is an opaque and internal object. We can't access it by scripts, and we can't read anything from it.
What you could do, is to use a Path2D
object directly.
To make use of the context current transform like you did in OP, you can use a DOMMatrix object, and the Path2D#addPath(path, matrix)
method, which will apply the matrix on the added path:
const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");
const mat = new DOMMatrix()
.translate(2, 2)
.scale(2, 2);
const p1 = new Path2D();
p1.moveTo(30, 50);
p1.lineTo(150, 100);
const p2 = new Path2D();
p2.addPath(p1, mat);
ctx.strokeStyle = "red";
ctx.stroke(p2);
<canvas height=500></canvas>