0

I've got a canvas on my consent form where users will sign and the data will be saved as base64 data.

Only problem is the canvas is respecting the padding of the controls around it so my top-left corner of my canvas isn't the top-left corner anymore:

<div class="p-3">
    <div class="card">
        <div class="card-body">
            <form method="post">
                <canvas width="400" height="400" id="can"></canvas>
            </form>
        </div>
    </div>
</div>

I'd have done a snippet but I'm too stupid to add bootstrap into the damn thing.

In this example, the p-3 class adds padding, the card div adds padding and the card-body might also do as well.

Result is I'm now drawing at least a couple of pixels below and to the right of where my cursor actually is.

Pictured here, the cursor is exactly at the right end of the line drawn.

How do I adjust for this in drawing the line?

When drawing, JS uses the client height and width to position the points against the canvas offsets... at least that's my understanding anyways (I've never worked with canvas before).

prevX = currX;
prevY = currY;
currX = e.clientX - canvas.offsetLeft;
currY = e.clientY - canvas.offsetTop;
draw();

Since the client isn't changing I assume the padding is added to the offsets... but I don't know what to do about it.

ANy help is appreciated.

enter image description here

psiodrake
  • 316
  • 1
  • 9

1 Answers1

0

I struggeled with this quite a bit myself. Here is the solution I found works best:

// Mouse positions relative to canvas
const canvasBoundingClientRect = canvas.getBoundingClientRect();
const mouseX = e.pageX - canvasBoundingClientRect.left;
const mouseY = e.pageY - canvasBoundingClientRect.top;

The function getBoundingClientRect() will give you the position of your canvas relative to your viewport.

e.pageX/Y is also preferred in case you can scroll on your page. Here is the explanation of the difference between pageX/Y and clientX/Y.

kny_92
  • 31
  • 4