0

The code snippet below is a web app that lets the user blend two images of the same dimensions. I am looking for a way to download the resulting image. The reason I am having this problem is because these are simply two images stacked on top of one another. One solution I can think of is to use a canvas. However, I'm not sure how to use a canvas for this situation.

var dimensions = [null, null];

function compareArray(arr1, arr2) {
  return arr1[0] == arr2[0] && arr1[1] == arr2[1];
}

function update(input, id) {
  var reader = new FileReader();

  reader.onload = function(event) {
    var image = new Image();
    image.src = event.target.result;

    image.onload = function() {
      if (id == 'img1' && dimensions[1] == null) {
        $('#img1').attr('src', event.target.result);
        dimensions[0] = [this.width, this.height];
      } else if (id == 'img2' && dimensions[0] == null) {
        $('#img2').attr('src', event.target.result);
        dimensions[1] = [this.width, this.height];
      } else if (id == 'img1') {
        if (compareArray([this.width, this.height],dimensions[1])) {
          $('#img1').attr('src', event.target.result);
          dimensions[0] = [this.width, this.height];
        } else {
          alert('Image dimensions must match.');
        }
      } else {
        if (compareArray([this.width, this.height],dimensions[0])) {
          $('#img2').attr('src', event.target.result);
          dimensions[1] = [this.width, this.height];
        } else {
          alert('Image dimensions must match.');
        }
      }
    }
  }

  reader.readAsDataURL(input.files[0]);
}

function opacityUpdate(value) {
  var percent1 = value;
  var percent2 = 100 - value;
  $('#percent1').html(percent1 + '%');
  $('#percent2').html(percent2 + '%');

  $('#img1').css('opacity', percent1 / 100);
  $('#img2').css('opacity', percent2 / 100);
}
img {
    position: fixed;
    opacity: 0.5;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='file' onchange='update(this, "img1");'>
<input type='file' onchange='update(this, "img2");'>
<br>
<table>
  <tr>
    <td id='percent1' style='width:40px;'>50%</td>
    <td><input type='range' min='0' max='100' value='50' id='range' oninput='opacityUpdate(this.value)'></td>
    <td id='percent2'>50%</td>
  </tr>
</table>
<img id='img1' src='#'>
<img id='img2' src='#'>

1 Answers1

0

I used Html2Canvas library for my project. I think it may fit you requirement. Here is the link for the library https://github.com/niklasvh/html2canvas

html2canvas(document.getElementById('yourDiv')).then(function(canvas) {
    document.body.appendChild(canvas); // or do something to the canvas
});

If you put one more div to warp two images, you can use the code below to get the a single element(canvas).

Kevin
  • 1,271
  • 9
  • 14