DEV Community

So Sun Park
So Sun Park

Posted on

html canvas scrolling and mouse position issue

Problem.

  • I have to draw ellipses when I click mouse on html canvas
  • The canvas is huge. maximum upto 1024px.
  • when I scroll down the page, the half of canvas is hidden.
  • when I try to paint at such position, the coordinates where the ellipses are drawn don't match my mouse position.

Before:

const { x, y, top, left } = this.ctx.canvas.parentNode.getBoundingClientRect();

this.offsetX = this.ctx.canvas.offsetLeft + x;
this.offsetY = this.ctx.canvas.offsetTop + y;
let mouseX = e.clientX - this.offsetX;
let mouseY = e.clientY - this.offsetY;

context.beginPath();
context.fillStyle = color;

        // Draw the ellipse
        context.ellipse(
            mouseX, mouseY, 
            size, size, 
            0, 0, Math.PI * 2
        );
context.fill();
context.closePath();
Enter fullscreen mode Exit fullscreen mode

reference: https://stackoverflow.com/questions/72379573/get-canvas-pixel-position-from-mouse-coordinates

After

const { bottom, height, left, right, top, width, x, y } = this.canvasWrapper.getBoundingClientRect();

const mouseX = (e.clientX - left) / width * this.canvas.width;
const mouseY = (e.clientY - top) / height * this.canvas.height;

Enter fullscreen mode Exit fullscreen mode

Top comments (0)