Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you combine multiple images into a single one using JavaScript?

I am wondering if there is a way to combine multiple images into a single image using only JavaScript. Is this something that Canvas will be able to do. The effect can be done with positing, but can you combine them into a single image for download?

Update Oct 1, 2008:

Thanks for the advice, I was helping someone work on a js/css only site, with jQuery and they were looking to have some MacOS dock-like image effects with multiple images that overlay each other. The solution we came up with was just absolute positioning, and using the effect on a parent <div> relatively positioned. It would have been much easier to combine the images and create the effect on that single image.

It then got me thinking about online image editors like Picnik and wondering if there could be a browser based image editor with photoshop capabilities written only in javascript. I guess that is not a possibility, maybe in the future?

like image 497
Steve T Avatar asked Oct 01 '08 17:10

Steve T


1 Answers

I know this is an old question and the OP found a workaround solution, but this will work if the images and canvas are already part of the HTML page.

<img id="img1" src="imgfile1.png">
<img id="img2" src="imgfile2.png">
<canvas id="canvas"></canvas>

<script type="text/javascript">
var img1 = document.getElementById('img1');
var img2 = document.getElementById('img2');
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');

canvas.width = img1.width;
canvas.height = img1.height;

context.globalAlpha = 1.0;
context.drawImage(img1, 0, 0);
context.globalAlpha = 0.5; //Remove if pngs have alpha
context.drawImage(img2, 0, 0);
</script>

Or, if you want to load the images on the fly:

<canvas id="canvas"></canvas>
<script type="text/javascript">
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var img1 = new Image();
var img2 = new Image();

img1.onload = function() {
    canvas.width = img1.width;
    canvas.height = img1.height;
    img2.src = 'imgfile2.png';
};
img2.onload = function() {
    context.globalAlpha = 1.0;
    context.drawImage(img1, 0, 0);
    context.globalAlpha = 0.5; //Remove if pngs have alpha
    context.drawImage(img2, 0, 0);
};        

img1.src = 'imgfile1.png';
</script>
like image 166
mikeslattery Avatar answered Oct 13 '22 00:10

mikeslattery