best way to convert a div to image? using either php, javascript or jquery

I have a div containing images like so:

<div id="Created_Design">
  <img src="images/image1.png" style="position: absolute; left: 8px; top: 172px;">
  <img src="images/image2.png" style="position: absolute; left: 20px; top: 144px">
</div>

I want to export this div to be an image cause im creating something like a design generator. So far what i have done is place the newly created design on new window using window.open like a preview of the design.

So my questions are:

  1. Can I convert this div and save it directly as an image?
  2. I was thinking of exporting this to a canvas so that I can save it as an image. How can I export this to canvas?
  3. Is there other way of doing this?

Answers:

Answer

I'll answer your question of porting what you have to a canvas. I wrote a post here.

What you do is read the images and their css position, top and left. Then copy it into the canvas.

(code from head, may be error)

// Loop over images and call the method for each image node
$('#Created_Design').children(function() {
    drawImage(this.src, this.style.left, this.style.top);
});

function drawImage(src, x, y) {
  var ctx = document.getElementById('canvas').getContext('2d');
  var img = new Image();
  img.onload = function() {
    ctx.drawImage(img, x, y);
  };
  img.src = src;
}
Answer

You can draw images from the div on the canvas using method drawImage(), after that you can get resulting base64-encoded image using toDataURL() method.

Answer

I would use php's GD library to create the new image. You can use the div's inline style to figure out the positioning needed for the new image. You'll need to spend some time reading the GD documentation I linked to first, it can be a bit confusing if you haven't used GD before but it can provide a lot of flexibility when working with images in php.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.