0

I am trying to use the Vuejs Draw Canvas of this Codepen as a component. Everything works great but the mouse position is relative to the window I think. So when drawn it works perfectly fine only if the canvas is window size ( width, height) if not there is a huge difference in the cursor and draw position.

I have tried setting the canvas width and height to offset instead of window like

setSize() {
   this.c.width = this.c.offsetWidth;
   this.c.height = this.c.offsetHeight - 60;
}

and mouse positions with below code as in this SO answers

function getMousePos(canvas, evt) {
    var rect = canvas.getBoundingClientRect();
    return {
        x: (evt.clientX - rect.left) / (rect.right - rect.left) * canvas.width,
        y: (evt.clientY - rect.top) / (rect.bottom - rect.top) * canvas.height
    };
}

but it did not change the result. So reverted back and added in code sandbox. If anyone can help me find out what the issue here? I know it's with mouse position but not sure exactly where.

Here is codesandbox link of the demo im trying to fix.

MJN
  • 610
  • 1
  • 7
  • 19

2 Answers2

0

I use these two methods (not sure without further digging why they are not the same):

canv = document.getElementById("id-of-canvas-object")

function mouseLocation(e)
{
 if (e.preventDefault)
    e.preventDefault();
 var x = e.PageX; var y = e.PageY;
// in one instance
 var relativeX = x - canv.offsetLeft;
 var relativeY = y - canv.offsetTop;
// in another instance
  var rect = canv.getBoundingClientRect();
  relativeX = x - rect.left;
  relativeY = y - rect.top;
}
T G
  • 445
  • 3
  • 7
0

On the example you shared you are not taking in count the offset when re positioning the cursor and you're substracting a 60px offset that is unnecessary because of the fixed positioning of the controls.

There are just 2 differences on lines: 234 & 239

setSize() {
  this.c.width = this.c.offsetWidth;
  this.c.height = this.c.offsetHeight; // <--- HERE i removed the -60px offset
}

moveMouse(e) {
  let x = e.offsetX;
  let y = e.offsetY + 60; // <--- HERE i added the 60px offset
  // the ´e.offsetY´ is relative to the canvas but you have an offset
  // for the controls that is moving the cursor (the little dot) to the top

  var cursor = document.getElementById("cursor");

  cursor.style.transform = `translate(${x}px, ${y}px)`;
}

Heres the example fixed: Fixed codesandbox

Note: I recommend to change the fixed positioning of the controls and manage everything with fixed height and width values or use flexbox to grow the canvas as it needs to.

German Meza
  • 146
  • 8