title: JavaScript - Wrong mouse position when drawing on canvas
body: <p>Here's a fiddle of the problem:</p>
  
  <p><a href="https://jsfiddle.net/y5cu0pxf/" rel="noreferrer">https://jsfiddle.net/y5cu0pxf/</a></p>
  
  <p>I've searched and tried so much but can't find the problem. I just want the pen to draw exactly where the mouse is clicked, but it's offset for some reason.</p>
  
  <p>Any ideas?</p>
  
  <p>Here's the code:</p>
  
  <pre><code>var imageLoader = document.getElementById('imageLoader');
  imageLoader.addEventListener('change', handleImage, false);
  
  var canvas = document.getElementById('imageCanvas');
  var ctx = canvas.getContext('2d');
  
  function handleImage(e){
  
    var reader = new FileReader();
  
    reader.onload = function(event){
  
      var img = new Image();
  
      img.onload = function(){
  
        canvas.width = window.innerWidth * 0.5;
        canvas.height = window.innerHeight;
  
        var hRatio = canvas.width / img.width;
        var vRatio =  canvas.height / img.height;
        var ratio = Math.min (hRatio, vRatio);
        var centerShift_x = (canvas.width - (img.width * ratio)) / 2;
        var centerShift_y = (canvas.height - (img.height * ratio)) / 2;
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        ctx.drawImage(img, 0, 0, img.width, img.height,
                      centerShift_x, centerShift_y, img.width * ratio, img.height * ratio);
      }
  
      img.src = event.target.result;
    }
    reader.readAsDataURL(e.target.files[0]);
  }
  
  var isDrawing;
  var rect = canvas.getBoundingClientRect();
  var offsetX = rect.left;
  var offsetY = rect.top;
  
  canvas.onmousedown = function(e) {
    isDrawing = true;
    ctx.moveTo(e.clientX - offsetX, e.clientY - offsetY);
  };
  canvas.onmousemove = function(e) {
    if (isDrawing) {
      ctx.lineTo(e.clientX - offsetX, e.clientY - offsetY);
      ctx.stroke();
    }
  };
  canvas.onmouseup = function() {
    isDrawing = false;
  };
  </code></pre>