开发者

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="ima开发者_如何学Cges/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?


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;
}


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜