【问题标题】:Create an image out of an svg + divs with bg-image使用 bg-image 从 svg + divs 创建图像
【发布时间】:2018-08-31 00:13:46
【问题描述】:

我想将一些 HTML(svg + div 和 bg 图像)转换为实际图像,并使用 JS + PHP 将其保存到目录。

这是一个 HTML 示例:

https://jsfiddle.net/9k7u32s4/7/

HTML

<img src="http://svgur.com/i/5x3.svg" alt="">
<div>
  <img src="http://svgur.com/i/5wM.svg" alt="">
  <div class="d1" style="background-image: url(https://picsum.photos/400/250/?image=114)"></div>
  <div class="d2" style="background-image: url(https://picsum.photos/400/250/?image=115)"></div>
  <div class="d3" style="background-image: url(https://picsum.photos/400/250/?image=116)"></div>
</div>

CSS

html,body{
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

body > img{
  height: 24rem;
  position: absolute;
  display: block;
  left: 0;
  right: 0;
  bottom: 0;
  margin: auto;
  top: 0;
  z-index: 20;
}

body > div > img{
  height: 24rem;
  position: relative;
  display: block;
  left: 0;
  right: 0;
  opacity: 0;
  bottom: 0;
  margin: auto;
  top: 0;
}

body > div{
  position: relative;
  z-index: 15;
}

body > div > div{
  background-size: cover;
  background-repeat: no-repeat;
  background-position: center;
  width: 100%;
  height: calc(100% / 3);
  position: absolute;
  left: 0;
}

body > div > .d1{
  top: 0;
}

body > div > .d2{
  top: calc(100% / 3);
}

body > div > .d3{
  top: calc((100% / 3) * 2);
}

看起来是这样的:

这是将其转换为图像后的样子:

实现这一目标的最简单方法是什么?提前致谢!

【问题讨论】:

    标签: javascript php html css svg


    【解决方案1】:

    最准确的方法是在&lt;canvas&gt; 元素中构建您的图像。为此,您可以使用 ctx.drawImage 将 dom 元素添加到画布并定位它们(​​svg 和您的背景图像)。

    这样您就可以使用canvas.toDataURL("image/png") 并在制作完成后将其保存为图像。那是JS部分。获得文件后,使用 PHP 将其保存到数据库中。

    那里有像https://html2canvas.hertzen.com/ 这样的库,你可以尝试一下,它们采用 dom 对象并将它们制作成 png,但它们并不总是最准确的,因为它们必须适应各种 css 选择器等等

    【讨论】:

    • 嗨,我试过使用 html2canvas 但 SVG 不起作用:/
    • 问题是 SVG 没有渲染,所以它们掩盖了所有其他的东西,所以我在画布制作后手动绘制了 SVG,谢谢!
    猜你喜欢
    • 2021-04-02
    • 1970-01-01
    • 1970-01-01
    • 2021-10-26
    • 2011-06-20
    • 1970-01-01
    • 2011-03-08
    • 2019-03-26
    • 2011-02-19
    相关资源
    最近更新 更多