0

I have tried a few solutions on SO but they didn't work for my setup. For some reason the mouse position is off on my canvas. I have pasted my HTML and JS below for reference.

The mouse works fine when the canvas size matches the window size, but I need it to work well when it is smaller or bigger too. How can I do this?

HTML

<canvas id="canvas"></canvas>

JS

window.addEventListener('load', () => {
    const canvas = document.querySelector('#canvas');
    const ctx = canvas.getContext('2d');

        // canvas.height = window.innerHeight;
        // canvas.width = window.innerWidth;

        canvas.height = 540;
        canvas.width = 960;
        
        // canvas.height = canvas.offsetHeight;
        // canvas.width = canvas.offsetWidth;

    let painting = false;

    var gradient = ctx.createLinearGradient(0, 0, 170, 0);
    gradient.addColorStop("0", "magenta");
    gradient.addColorStop("0.5", "blue");
    gradient.addColorStop("1.0", "red");

    function windowSize() {
        // canvas.height = window.innerHeight;
        // canvas.width = window.innerWidth;
        // canvas.height = 540;
        // canvas.width = 960;
        // canvas.height = canvas.offsetHeight;
        // canvas.width = canvas.offsetWidth;
    }
    function startPosition(e) {
        painting = true;
        draw(e);
    }
    function finishedPosition() {
        painting = false;
        ctx.beginPath();
    }
    function draw(e) {
        if(!painting) return;
        ctx.lineWidth = lineSize;
        ctx.lineCap = "round";
        ctx.strokeStyle = color;

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

    var lineSize = 5;
    var color = "Black";

    // Event Listeners

    canvas.addEventListener('mousedown', startPosition);
    canvas.addEventListener('mouseup', finishedPosition);
    canvas.addEventListener('mousemove', draw);
    canvas.addEventListener('touchstart', startPosition);
    canvas.addEventListener('touchend', finishedPosition);
    canvas.addEventListener('touchmove', draw);
    // window.addEventListener('resize', windowSize);

});
grahamfk45c
  • 83
  • 1
  • 9
  • Does this answer your question? [Mouse position within HTML 5 responsive Canvas](https://stackoverflow.com/questions/28628964/mouse-position-within-html-5-responsive-canvas) – Lawrence Cherone Jul 11 '20 at 14:00

1 Answers1

0

The accepted solution here solved my problem. I hope this helps someone else in the future, as it did not appear high in search results.

Real mouse position in canvas

grahamfk45c
  • 83
  • 1
  • 9