将 div 转换为图像的最佳方法?使用 php、javascript 或 jquery

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6825262/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 21:59:18  来源:igfitidea点击:

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

phpjavascriptjquery

提问by matrix_12

I have a div containing images like so:

我有一个包含像这样的图像的 div:

<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.

我想将此 div 导出为图像,因为我正在创建类似设计生成器的东西。到目前为止,我所做的是使用 window.open 将新创建的设计放在新窗口上,就像设计预览一样。

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?
  1. 我可以转换这个 div 并将其直接保存为图像吗?
  2. 我正在考虑将其导出到画布,以便将其保存为图像。如何将其导出到画布?
  3. 有没有其他方法可以做到这一点?

回答by Shawn Mclean

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.

您要做的是读取图像及其 css 位置、顶部和左侧。然后将其复制到画布中。

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

回答by bjornd

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.

您可以使用 method 从画布上的 div 绘制图像drawImage(),之后您可以使用 method获取生成的 base64 编码图像toDataURL()

回答by AdamP

I would use php's GDlibrary 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.

我会使用 php 的GD库来创建新图像。您可以使用 div 的内联样式来确定新图像所需的定位。您需要花一些时间阅读我首先链接到的 GD 文档,如果您之前没有使用过 GD 可能会有点混乱,但是在 php 中处理图像时它可以提供很大的灵活性。