I am trying to convert a DIV to single image. The div has 4 images in it. I have found the js for \"htmltocanvas\" but this jquery plugin does not create image with all images p
jQuery
var s=0;
$('#myJershy').children('img').each(function(){
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var img=document.getElementById($(this).attr('id'));
ctx.drawImage(img,s,10,$(this).width(),$(this).height());
s=s+$(this).width();
});
If you want that the position of divs in canvas should be exactly as displayed outside canvas then see the below fiddle:
Here is my answer (based on @Zwords awesome answer) which takes the Top and Left positions into account. In case you want to layer those images.
$('#myJershy').children('img').each(function(){
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var img=document.getElementById($(this).attr('id'));
ctx.drawImage(img,$(this).css('left').replace('px',''),$(this).css('top').replace('px',''),$(this).width(),$(this).height());
});
Forked Fiddle from @Zword
Here's my attempt:
http://jsfiddle.net/8FFQM/1/
Don't worry about those huge codes in the html, they're just the images url-encoded, you don't have to do it if your images are hosted on your domain.
The exported image as jpg is the one with red boarder (scroll around in the result window):
var DivsToJPG = function( parent ) {
this.canvasSizeX = 0;
this.canvasSizeY = 0;
this.init = function( parent ) {
this.images = parent.find('img');
this.setSizes();
this.createCanvas();
this.drawImages();
this.exportJPG();
}
this.setSizes = function() {
for (var i = 0, l = this.images.length; i < l ; i++) {
var currentImage = this.images.eq(i);
var posX = currentImage.position().left;
var width = currentImage.width();
this.canvasSizeX = this.canvasSizeX > (posX+width) ? this.canvasSizeX : posX + width;
//console.log(this.canvasSizeX);
var posY = currentImage.position().top;
var height = currentImage.height();
this.canvasSizeY = this.canvasSizeY > (posY+height) ? this.canvasSizeY : posY + height;
}
}
this.createCanvas = function() {
this.canvas = document.createElement('canvas');
this.canvas.id = "exportCanvas";
this.canvas.width = this.canvasSizeX;
this.canvas.height = this.canvasSizeY;
this.ctx = this.canvas.getContext("2d");
document.body.appendChild(this.canvas);
}
this.drawImages = function() {
for (var i = 0, l = this.images.length; i < l ; i++) {
var currentImage = this.images[i];
var $currentImage = this.images.eq(i);
this.ctx.drawImage(currentImage, $currentImage.position().left, $currentImage.position().top, $currentImage.width(), $currentImage.height());
}
}
this.exportJPG = function() {
var dataURL = this.canvas.toDataURL();
this.img = document.createElement('img');
this.img.id = "createdImage";
this.img.src = dataURL;
document.body.appendChild(this.img);
}
this.init( parent );
}
var divsToJPG = new DivsToJPG($('#myJershy'));
PS: it's a bit longer but it should take care of everything, it uses a bit of jQuery