[英]Html2Canvas and Canvas2Image not work on page
I have this simple code to save html as image: 我有以下简单代码将html保存为图像:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script src="js/jquery.js"></script>
<script src="js/html2canvas.js"></script>
<script src="js/canvas2image.js"></script>
<script>
$('#save').click(function () {
var elem = $('#element').get(0);
var leba = "600";
var ting = "400";
var type = "bmp";
var name = "temp"
html2canvas(elem).then(function (canvas) {
var cWidth = canvas.width;
var cHeight = canvas.height;
var img = Canvas2Image.convertToImage(canvas, cWidth, cHeight);
$('#preview').after(img);
Canvas2Image.saveAsImage(canvas, leba, ting, type, name);
})
})
</script>
<div id="element"
style="width: 600px; height: 450px; background-color: aquamarine; margin: 30px auto; text-align: center">
<h1>Screenshot</h1>
<input type="text" style="background-color: aliceblue; border: 1px solid #aaaaaa; color: #333333">
</div>
<div style="text-align: center">
<button id="save">Salva</button>
<p id="preview"></p>
</div>
</body>
</html>
I want to have a preview of the screenshot and save it on click, but when I click nothing happens. 我想要预览屏幕截图并单击保存,但是单击时什么也没有发生。
The three files containing the three scripts are correctly loaded, I'm using visual studio code and the links are correct, but despite the attempts, I can't get the image. 包含三个脚本的三个文件已正确加载,我使用的是Visual Studio代码,并且链接正确,但是尽管尝试了,但仍无法获取图像。
I also tried to put the js links directly, but without success, I moved the scripts directly into the HTML tag (I know it's useless), but my page doesn't give any results. 我也尝试直接放置js链接,但是没有成功,我将脚本直接移动到HTML标记中(我知道它没有用),但是我的页面没有任何结果。
For saving the canvas as image you can go through the below change. 要将画布另存为图像,可以进行以下更改。 I dont think so, that you need a library to save the file. 我不这么认为,您需要一个库来保存文件。
html2canvas(document.querySelector("#element")).then(function (canvas) {
var dataURL = canvas.toDataURL("image/jpeg", 1.0);
var a = document.createElement('a');
a.href = dataURL;
a.download = 'untitled.jpeg';
document.body.appendChild(a);
a.click();
})
And for the complete reference you can visit the CodePen link added below 对于完整的参考,您可以访问下面添加的CodePen链接
https://codepen.io/mukeshmohan/pen/ymvQjV https://codepen.io/mukeshmohan/pen/ymvQjV
And its recommended to wrap your code inside a document ready. 并且建议将您的代码包装在文档中。
$( document ).ready(function() {
// your script goes here
});
which will make the jquery to wait till the dom rendering completes, that allows a safe and clean event handling. 这将使jquery等待dom渲染完成,从而允许安全干净的事件处理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.