title: Javascript - Draw on canvas using percentage of width & height
body: <p>I have a background image that takes up the full width and height of my canvas, and I want to be able to reference different locations on the image, so I am placing some circles at those points in the image so I can visually confirm I have the right spot.</p>
  
  <p>I'm doing this by click the mouse at the spot where I want to draw a dot, with the following code in my mouse click listener event:</p>
  
  <pre><code>var rectCanvas = canvas.getBoundingClientRect();
  var positionX = Math.round(((e.clientX - rectCanvas.left) / canvas.width * 100) * 1000) / 1000;
  var positionY = Math.round(((e.clientY - rectCanvas.top) / canvas.height * 100) * 1000) / 1000;
  
  //alert(positionX + ", " + positionY);
  
  alert("Width\nPosition: " + (e.clientX - rectCanvas.left) + "\nPercentage Position: " + positionX + "\nBack to position: " + percentToPxHor(positionX));
  </code></pre>
  
  <p>I have the following routines declared:</p>
  
  <pre><code>function percentToPxHor(intPx) {
      return intPx * canvas.width / 100;
  }
  
  function percentToPxVert(intPx) {
      return intPx * canvas.height / 100;
  }
  </code></pre>
  
  <p>Clicking on a notable feature of the background image, I get a value which makes sense.  For example, clicking about halfway across the image prompts me with:</p>
  
  <blockquote>
    <p>Width<br>
    Position: 532.5<br>
    Percentage Position: 53.091<br>
    Back to position: 532.50273  </p>
  </blockquote>
  
  <p>From this I can clearly tell my routine for converting a percentage of the width back to a pixel value works.  However, when I try to put this into practice, it doesn't work.</p>
  
  <p>When trying to draw the circles I mentioned earlier, it places them correctly on the Y axis, but too far to the right on the X axis.  I suspect this has something to do with the way I take into account the position of the canvas in relation to the window, but I can't quite put my finger on it.  Circles placed on the left hand side of the image are slightly too far right, those placed more to the right hand side of the image are greatly too far right (almost as if whatever the problem is, it's applying an exponential problem that gets worst the bigger the numbers involved.</p>
  
  <p>When I add these circles, I place four, one on each corner of a rectangle, using the following snippet of code:</p>
  
  <pre><code>var topLeft = {x:percentToPxHor(17.275),y:percentToPxVert(59.691)};
  var bottomLeft = {x:percentToPxHor(17.275),y:percentToPxVert(60.72)};
  var topRight = {x:percentToPxHor(71.459),y:percentToPxVert(61.407)};
  var bottomRight = {x:percentToPxHor(71.352),y:percentToPxVert(62.436)};
  </code></pre>
  
  <p>Any help would be greatly appreciated.</p>