How to embed a small image on top of another image and save it using JavaScript?

ⅰ亾dé卋堺 提交于 2019-12-05 19:16:46
kubetz

If the images are on the same origin the it is possible to use canvas.

  • draw images to canvas
  • call canvas.toDataURL() to retrieve the image data
  • create img element and append data to it

Example:

HTML:

<img id="main" src="image1" />
<img class="small" src="image2" data-posx="0" data-posy="0" />
<img class="small" src="image3" data-posx="50" data-posy="50" />
<div id="result"></div>

JavaScript:

function process(main, rest) {
  var canvas = document.createElement("canvas");
  canvas.width = main.width;
  canvas.height = main.height;

  var ctx = canvas.getContext("2d");
  ctx.drawImage(main, 0, 0);

  for (var i = 0; i < rest.length; i++) {
    var img = rest[i];
    ctx.drawImage(img, img.getAttribute("data-posx"), img.getAttribute("data-posy"));
  }

  return canvas.toDataURL("image/png");
}

var img = document.createElement("img");
img.src = process(document.getElementById("main"),  document.getElementsByClassName("small"));
document.getElementById("result").appendChild(img); 

If you want to write the image on [0, 0] coordinates then you don't have to use data- attributes, of course. Problem with this approach is that if the files are hosted on different origin then toDataURL will throw security error.

Based on: https://stackoverflow.com/a/934925/1011582

Note: I would like to link jsfiddle or jsbin example but because of the same origin policy I cannot create any reasonably looking example. Any ideas?

THIS is the best example I was able to get (tested with Chrome & FF).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!