title: Mouse Position Off In HTML5 Canvas?
body: <p>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.</p>
  <p>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?</p>
  <p>HTML</p>
  <pre><code>&lt;canvas id=&quot;canvas&quot;&gt;&lt;/canvas&gt;
  </code></pre>
  <p>JS</p>
  <pre><code>window.addEventListener('load', () =&gt; {
      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(&quot;0&quot;, &quot;magenta&quot;);
      gradient.addColorStop(&quot;0.5&quot;, &quot;blue&quot;);
      gradient.addColorStop(&quot;1.0&quot;, &quot;red&quot;);
  
      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 = &quot;round&quot;;
          ctx.strokeStyle = color;
  
          ctx.lineTo(e.clientX, e.clientY);
          ctx.stroke();
          ctx.beginPath();
          ctx.moveTo(e.clientX, e.clientY);
      }
  
      var lineSize = 5;
      var color = &quot;Black&quot;;
  
      // 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);
  
  });
  </code></pre>