Skafec
Skafec

Reputation: 49

JS using wrong coordinates when drawing on canvas with margin

Hey guys I have problem with using canvas together with some basic CSS styling.

So I wanted to get myself familiar a little bit more with canvas element so I followed Dev Ed's (Youtube) tutorial on how to make a drawing app with canvas.

I wanted to upgrade it a little bit by adding some color options for lines and background, added a title and so on. I wanted to center canvas element as well as give it fixed size.

Now when I'm trying to use it, canvas uses wrong coordinates to draw lines.

Thanks in advance.

Code that controls mouse coorinates:

function draw(e) {
  if (!painting) return;
  ctx.lineWidth = 10;
  ctx.lineCap = "round";

  ctx.lineTo(e.clientX, e.clientY);
  ctx.stroke();
  ctx.beginPath();
  ctx.moveTo(e.clientX, e.clientY);
}

Link to full code on codepen: https://codepen.io/Skafec/pen/NWKzxrg

Upvotes: 0

Views: 1095

Answers (1)

F.Igor
F.Igor

Reputation: 4350

I recently created a couple of functions for that. The real coordinate is a composition of pointer position, translated using the bounding rect position, and apply a factor ( real size vs display size)

function translatedX(x){
    var rect = canvas.getBoundingClientRect();
    var factor = canvas.width / rect.width;
    return factor * (x - rect.left);
}

function translatedY(y){
    var rect = canvas.getBoundingClientRect();
    var factor = canvas.width / rect.width;
    return factor * (y - rect.top);
}

See https://codepen.io/fraigo/pen/jONKWaz

Upvotes: 6

Related Questions