title: Draw a rectangle on a image inside a canvas using mousemove event in javascript
body: <p>I am trying to draw a rectangle on an image that is inside canvas using mousemove event . But i am getting rectangle on the image with color filled in the rectangle because of clearRect . can anyone figure me out . how to draw a rectangle with just a border on the image . Below is the code that i followed to achieve it .</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>var canvas = document.getElementById('canvas'),
      ctx = canvas.getContext('2d'),
      rect = {},
      drag = false;
   function init() {
    var imageObj = new Image();
  
        imageObj.onload = function() {
          ctx.drawImage(imageObj, 0, 0);
        };
        imageObj.src = 'http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg';
     canvas.addEventListener('mousedown', mouseDown, false);
     canvas.addEventListener('mouseup', mouseUp, false);
     canvas.addEventListener('mousemove', mouseMove, false);
   }
   function mouseDown(e) {
     rect.startX = e.pageX - this.offsetLeft;
     rect.startY = e.pageY - this.offsetTop;
     drag = true;
   }
   function mouseUp() {
     drag = false;
   }
   function mouseMove(e) {
     if (drag) {
    rect.w = (e.pageX - this.offsetLeft) - rect.startX;
    rect.h = (e.pageY - this.offsetTop) - rect.startY ;
    ctx.clearRect(rect.startX, rect.startY,rect.w,rect.h);
    draw();
     }
   }
   function draw() {
     ctx.clearRect(rect.startX, rect.startY, rect.w, rect.h);
     ctx.strokeRect(rect.startX, rect.startY, rect.w, rect.h);
   }</code></pre>
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;head&gt;
  &lt;meta charset="utf-8" /&gt;
  &lt;title&gt;Draw a rectangle!&lt;/title&gt;
  &lt;/head&gt;
  
  &lt;body onload="init();"&gt;
  &lt;canvas id="canvas" width="500" height="500"&gt;&lt;/canvas&gt;
  &lt;/body&gt;</code></pre>
  </div>
  </div>
  </p>