Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

115
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda