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();
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;
Top comments (0)