Div to img HTML2Canvas

Div to img HTML2Canvas

本文关键字:HTML2Canvas img to Div      更新时间:2023-09-26

我试图使用html2canvas将div转换为img,这个过程之后的问题最终图像忽略了我在div中的图像,只显示文本:https://gist.github.com/martinop/cc20969f49b2bb116617https://gist.github.com/martinop/5fd0199d800ee2ffe313

如果我在css中使用其他方式,如background-img,当我点击按钮时,我有这个错误:未捕获的SecurityError:未能在'HTMLCanvasElement'上执行'toDataURL':受污染的画布可能无法导出

你需要给出图像的完整路径,以便使用html2canvas创建div图像

例如

<img src="https://avatars0.githubusercontent.com/u/10482079?s=140" class="img">

我已经测试了这个和它的工作为我。它也适用于chrome…在chrome

中运行代码

$(window).load(function(){
    $('#load').click(function(){
            html2canvas($('#testdiv'), {
                onrendered: function (canvas) {
                    var img = canvas.toDataURL("image/png")
                    window.open(img);
                }
            });
    });
});
div#testdiv
{
    height:500px;
    width:500px;
    position: relative; 
}
 
.fuente{
	font-family: 'Chewy', cursive;
	margin-left: 50px;
	margin-bottom: 50px;
}
h1{
	color: #EE1F3B;
    text-shadow: 1px 1px 2px black;
    font-size: 70px;
 
}
.img{
	width: 100px;
	height: 100px;
}
.imgequipo{
   position: absolute; 
   top: 90px; 
   left: 335px; 
  width: 100px;
	height: 100px;
 
}
h2{
   position: absolute; 
   top: 110px; 
   font-family: 'Oswald', sans-serif;
   color: #ffe400;
   font-size:80px;
   font-weight: bold;
   left: 30px;   
 
}
 
body{
	margin-top: 100px;
	margin-bottom: 100px;
	background-color: #eeeeee;
}
<html>
<head>
<script src="http://html2canvas.hertzen.com/build/html2canvas.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link href='http://fonts.googleapis.com/css?family=Chewy' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Oswald' rel='stylesheet' type='text/css'>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class ="container">
<h1 class="fuente text-center">prueba</h1>
<div class="col-md-1 col-md-offset-3">
<div id="testdiv">
<img src="https://avatars0.githubusercontent.com/u/10482079?s=140" class="img">
<img src="https://avatars0.githubusercontent.com/u/10482079?s=140" class="imgequipo">
<h2>prueba2</h2>
</div><br>
<button  id="load" class="btn btn-info">Generar Imagen</button>
</div>
</div>
 
</body>
</html>