简体   繁体   中英

Html2Canvas and Canvas2Image not work on page

I have this simple code to save html as image:

<!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.

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.

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

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.

You need to wrap your code in a

$( document ).ready()

block

Take a look here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM