canvashtml5-canvascoordinates

Get Identity Matrix equivalent coordinates of any transformed space coordinates


ctx.setTransform(12,0,0,12,34,23)

ctx.fillText("a",0,0)

Is it possible to get the equivalent coordinates of "a" in identity matrix transformed space.

I want to pin point char "a" on mouse click.mouse coordinates acts as if 1,0,0,1,0,0 transform is set.

Thanks

I tried to modify mouse coordinates to the given transform but I want to know if there exist any simpler ways.


Solution

  • You can get the current matrix of the 2D context through its getTransform() method, and then you can convert your point in identity coordinates through this DOMMatrix's transformPoint() method.

    const target = document.querySelector(".target");
    const canvas = document.querySelector("canvas");
    const ctx = canvas.getContext("2d");
    ctx.setTransform(12,0,0,12, 100, 100);
    ctx.rotate(Math.random() * 180);
    ctx.translate(Math.random() * 7, Math.random() * 7);
    // Using an arc so it's clearer where it is on the context
    ctx.arc(0, 0, 2, 0, Math.PI * 2);
    ctx.fill();
    // Get the current matrix
    const mat = ctx.getTransform();
    const { x, y } = mat.transformPoint({ x: 0, y: 0 });
    console.log({ x, y });
    target.style.left = `${x}px`;
    target.style.top = `${y}px`;
    canvas, .target { position: absolute; top: 0; left: 0 }
    .target {
      display: inline-block;
      width: 10px;
      height: 10px;
      background: #FF00FFAA;
      translate: -5px -5px; /* centered */
    }
    <canvas width="200" height="200"></canvas>
    <div class="target"></div>