Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

116
Vistas
How to account for surrounding padding in canvas?

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

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

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.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda