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).