It is possible, yes, with the Canvas API (HTML5).
However, for security reasons, it is not possible to display the collage result in a <img>
tag, nor to download, if at least one of the input images comes from a different domain (server) strong> of the page.
The most important steps are described below. I provided an example *; just pay close attention to safety details; this code can be used both to display the result on the canvas and in the <img>
, just by choosing the right lines for the desired purpose.
Creating the canvas
It is indispensable because the images will be glued together on the canvas. Therefore, at this stage, it is important to also set the canvas size (see JSFiddle for example *). If you do not want to display the result on the canvas, but instead in a <img>
, simply remove the line from appendChild()
.
var canvas = document.createElement("canvas");
var context = canvas.getContext("2d");
output.appendChild(canvas); // opcional
Creating elements for input images
Required to be able to request files from the server's input images.
var img_in1 = document.createElement("img");
var img_in2 = document.createElement("img");
Listener of the first input image
As soon as the first image loads, it adds its pixels to the canvas and requests the second image. (To find out where to paste the second image inside the canvas, we already have the width of the first image .)
img_in1.addEventListener("load", function(){
context.drawImage(img_in1
, 0, 0, img_in1.width, img_in1.height
, 0, 0, img_in1.width, img_in1.height
);
img_in2.src = "/imagens/img2.png";
});
Second input image listener
When the second image loads, this code places it next to the first image on the canvas. If both images are from the same page domain, you have the option to display the collage result in a <img>
instead of the canvas .
img_in2.addEventListener("load", function(){
context.drawImage( img_in2
, 0, 0, img_in2.width, img_in2.height
, img_in1.width, 0, img_in2.width, img_in2.height
);
// Se as imagens vierem do mesmo domínio da página:
img_out.src = canvas.toDataURL("image/png");
botao.href = canvas.toDataURL("image/png");
});
Requesting the first input image
Unleash the whole process; if the first image is not loaded, none of the listeners will be warned and nothing will happen.
img_in1.src = "/imagens/img1.png";
I hope I have helped!
JSFiddle for example : updated to work with JSFiddle's own images, thus escaping from the constraint security.
Edit : I have two comments to make:
-
This method is robust . You can make very complex transformations with the images, thanks to the canvas, and also make the resulting assembly available for download at the end of the process.
-
@Jader method may be easier . If the goal is a simple assembly, intended only for the "static" view on the page itself, the CSS method uses much less script (JS).