HTML Div转换为带有背景图像Html2canvas的图像

HTML Div convert into image with background image Html2canvas

本文关键字:图像 背景 Html2canvas Div 转换 HTML      更新时间:2023-09-26

我把画布放进一个HTMLdiv,之后我使用Html2canvas将这个div转换为图像。HTMLdiv 转换成功,但背景图像未出现。

我看到了一个链接,但我不确定。因为我没有看到任何背景图像。Javascript html2canvas 无法获取背景

请告诉我任何想法。

$(function() { 
    $("#btnSave").click(function() { 
        html2canvas($("#html-to-canvas"), {
            onrendered: function(canvas) {
                theCanvas = canvas;
                document.body.appendChild(canvas);          
                Canvas2Image.saveAsPNG(canvas); 
                $("#canvas-image").append(canvas);              
            }
        });
    });
}); 
 .bg-img
   {
   		background-image:url('https://d2z4fd79oscvvx.cloudfront.net/0016463_petal_diamond_ring_320.jpeg');
   		background-repeat: no-repeat;
   		 
   }
<script src="http://code.jquery.com/jquery-1.9.0.min.js"></script>
<script src="https://raw.github.com/niklasvh/html2canvas/gh-pages/build/html2canvas.js"></script>
  
<script src="https://raw.github.com/niklasvh/html2canvas/v0.34/src/plugins/jquery.plugin.html2canvas.js"></script>
  <div style="width:450px;height:500px;border:1px solid #333" class=" html-to-canvas bg-img"   id="html-to-canvas">   
            <canvas id="canvas" style="margin-left:100px;margin-top:150px" width="200" height="300"></canvas>
   </div>
<input type="button" id="btnSave" value="Save PNG"/>
<div id="canvas-image"></div>

html2canvasCanvas2Image不适用于外部图像。

脚本使用的所有图像都需要驻留在同一源下,以便能够读取它们。裁判

对图像使用相对路径并尝试:

工作代码:

$(function() {
  $("#btnSave").click(function() {
    html2canvas($("#html-to-canvas"), {
      onrendered: function(canvas) {
        Canvas2Image.saveAsPNG(canvas);
        $("#canvas-image").append(canvas);
      }
    });
  });
});
.bg-img {
  background-image: url('images/0016463_petal_diamond_ring_320.jpeg');
  background-repeat: no-repeat;
}
<div style="width: 450px; height: 500px; border: 1px solid #333" class=" html-to-canvas bg-img" id="html-to-canvas">
  <canvas id="canvas" style="margin-left: 100px; margin-top: 150px" width="200" height="300"></canvas>
</div>
<input type="button" id="btnSave" value="Save PNG" />
<div id="canvas-image"></div>