title: javascript: upload image file and draw it into a canvas
body: <p>I work at a web application for painting images. I use a CANVAS element and javascript to draw on it, but I have a problem: how can I load an image from the pc of the user and draw it on the canvas? I don't want to save it on the server, only on the webpage!</p>
  
  <p>Here is a shortened version of the code (the full code would be too long):</p>
  
  <p>HTML:</p>
  
  <pre><code>Open file: &lt;input type="file" id="fileUpload" accept="image/*" /&gt;&lt;br /&gt;
  &lt;canvas id="canvas" onmousemove="keepLine()" onmouseup="drawLine()" onmousedown="startLine()" width="900" height="600" style="background-color:#ffffff;cursor:default;"&gt;
    Please open this website on a browser with javascript and html5 support.
  &lt;/canvas&gt;
  </code></pre>
  
  <p>javascript:</p>
  
  <pre><code>var x = 0;
  var y = 0;
  var clicked = false;
  
  var canvas = document.getElementById("canvas");
  var context = canvas.getContext("2d");
  
  context.strokeStyle = "black";
  context.lineCap = "round";
  
  canvas.addEventListener('mousemove', function(e) { getMousePos(canvas, e); }, false);
  
  takePicture.onchange = function (event) {
    var files = event.target.files,
      file;
    if (files &amp;&amp; files.length &gt; 0) {
      file = files[0];
      processImage(file);
    }
  };
  
  function processImage(file) {
    var reader = new FileReader();
    reader.readAsDataUrl(file)
    reader.onload = function(e) {
      var img = new Image();
      img.onload = function() {
        context.drawImage(img, 100,100)
      }
      img.src = e.target.result;
    }
  }
  
     // functions for drawing (works perfectly well)
  function getMousePos(canvas, e) {
    var rect = canvas.getBoundingClientRect();
    x = evt.clientX - rect.left;
    y = evt.clientY - rect.top;
  }
  
  function startLine() {
    context.moveTo(x,y);
    context.beginPath();
    clicked = true;
  }
  
  function keepLine() {
    if(clicked) {
      context.lineTo(x,y);
      context.stroke();
      context.moveTo(x,y);
    }
  }
  
  function drawLine() {
    context.lineTo(x,y);
    context.stroke();
    clicked = false;
  }
  </code></pre>
  
  <p>There's no copyright</p>