<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="html2canvas.js"></script>
<script type="text/javascript">
$(function() {
$("#btn").click(function() {
html2canvas($("#img_load"), {
onrendered: function(canvas) {
theCanvas = canvas;
document.body.appendChild(canvas);
Canvas2Image.saveAsPNG(canvas);
$("#img_preview").append(canvas);
}
});
});
});
</script>
</head>
<body>
<div id="img_load">
<img id="test" src="http://www.keenthemes.com/preview/metronic/theme/assets/global/plugins/jcrop/demos/demo_files/image1.jpg" style="width: 200px; height: 200px;"/>
</div>
<button id="btn" type="button">OK</button>
<div id="img_preview" style="border: 1px solid black; width: 200px; height: 200px;">
<canvas id="myCanvas" width="200" height="100"></canvas>
</div>
</body>
当我按下&#34; OK&#34;我想将该图片发送给我的&#34; img_preview&#34; DIV。但它创造了新的卡瓦斯而不是去那个div。请帮助我解决这个问题..
答案 0 :(得分:0)
您也可以在不使用画布的情况下执行此操作。以下是完整的工作代码。
<html lang="en">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#btn').click(function(){
$('#img_preview').html('<img src="' + $('#test').attr('src') + '" />');
});
});
</script>
</head>
<body>
<div id="img_load">
<img id="test" src="http://www.keenthemes.com/preview/metronic/theme/assets/global/plugins/jcrop/demos/demo_files/image1.jpg" style="width: 200px; height: 200px;"/>
</div>
<button id="btn" type="button">OK</button>
<div id="img_preview" style="border: 1px solid black; width: 200px; height: 200px;">
</div>
</body>
</html>
答案 1 :(得分:0)
它正在创建一个新的画布,因为你要附加它,替换为
<强>从强>
$("#img_preview").append(canvas);
以强>
$("#img_preview").html(canvas);
答案 2 :(得分:0)
不幸的是,你不可能抓住那张图片的画布,因为它来自外部服务器并且这是一个安全功能。
Security Error with canvas.toDataURL() and drawImage()
然而,你可以这样做。
<html>
<head>
<script type="text/javascript">
$(function () {
$("#btn").click(function () {
html2canvas($("#img_preview"), {
onrendered: function (canvas) {
//theCanvas = canvas;
//document.body.appendChild(canvas);
//Canvas2Image.saveAsPNG(canvas);
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = document.getElementById("test");
var x = 0;
var y = 0;
var width = 200;
var height = 200;
ctx.drawImage(img, x, y, width, height);
}
});
});
});
</script>
</head>
<body>
<div id="img_load">
<img id="test" src="http://www.keenthemes.com/preview/metronic/theme/assets/global/plugins/jcrop/demos/demo_files/image1.jpg" style="width: 200px; height: 200px;" />
</div>
<button id="btn" type="button">OK</button>
<div id="img_preview" style="border: 1px solid black; width: 200px; height: 200px;">
<canvas id="myCanvas" width="200" height="200"></canvas>
</div>
</body>
请参阅此处的工作示例:https://jsfiddle.net/copaq6ch/29/
希望这有帮助!快乐的编码!