title: How do I load a local image using JS?
body: <p>I want to load two separate images in my script. I've accomplished it using:</p>
  
  <pre><code>&lt;img src="iphone4.png" id="img1"&gt;
  &lt;img src="screenshot.png" id="img2"&gt;
  
  &lt;script&gt;
          window.onload = function () {
              var img1 = document.getElementById('img1');
              var img2 = document.getElementById('img2');
  &lt;/script&gt;
  </code></pre>
  
  <p>Problem here though is that the images should not be visible on the page but are when loaded using markup. I simply want to load them through the script without first having to add them in the markup. I realize this is an extremely trivial problem, but searching for a solution has given me nothing.</p>
  
  <p>I tried this approach:</p>
  
  <pre><code>        window.onload = function () {
              var img1 = "iphone4.png";
              var img2 = "screenshot.png";
  </code></pre>
  
  <p>But this did not work.
  Can someone with some common JS sense please give me some input on this issue.</p>
  
  <p><strong>EDIT :</strong>
  So this is how the markup/JS looks now, the images are still displayed and the final merge of the images won't show. The error I get is: </p>
  
  <pre><code>IndexSizeError: Index or size is negative or greater than the allowed amount
  [Stanna vid fel]    
  
  var image1 = context.getImageData(0, 0, width, height);
  </code></pre>
  
  <p>And this is the syntax:</p>
  
  <pre><code>&lt;body&gt;
      &lt;img src="" id="img1"&gt;
      &lt;img src="" id="img2"&gt;
      &lt;p&gt;Blended image&lt;br&gt;&lt;canvas id="canvas"&gt;&lt;/canvas&gt;&lt;/p&gt;
      &lt;script&gt;
          window.onload = function () {
              var img1 = document.getElementById('img1');
              var img2 = document.getElementById('img2');
  
              img1.src = "iphone4.png";
              img2.src = "screenshot.png";
  
              var canvas = document.getElementById("canvas");
              var context = canvas.getContext("2d");
              var width = img1.width;
              var height = img1.height;
              canvas.width = width;
              canvas.height = height;
  
              var pixels = 4 * width * height;
              context.drawImage(img1, 0, 0);
              var image1 = context.getImageData(0, 0, width, height);
              var imageData1 = image1.data;
              context.drawImage(img2, 73, 265);
              var image2 = context.getImageData(0, 0, width, height);
              var imageData2 = image2.data;
              while (pixels--) {
                  imageData1[pixels] = imageData1[pixels] * 0 + imageData2[pixels] * 1;
              }
              image1.data = imageData1;
              context.putImageData(image1, 0, 0);
          };
      &lt;/script&gt;
  </code></pre>