简体   繁体   中英

Save image from html2canvas inside a folder

I am creating an image of an HTML <div> . Its working fine and the image is rendered to another div using html2canvas.js.

Now I want to give a link so that anyone can download the image to a folder inside the application.

Sample code that I am using:

//html whose image will be created.
<div id="mydiv">
     <p>text!</p>
     <h1>This is a test!!</h1>
</div>

//div where image will be rendered.
<div id="image">
        <p>Image:</p>
</div>

//script to create image of html

<script type="text/javascript" src="/js/html2canvas.js"></script>
    <script type="text/javascript">
        html2canvas([document.getElementById('mydiv')], {
            onrendered: function (canvas) {

                var data = canvas.toDataURL('image/gif');
                var image = new Image();
                image.src = data;
                document.getElementById('image').appendChild(image);

            }
        });
    </script>

在此处输入图片说明 Kindly suggest.

This is usually done using some server side tools to actually store the image somewhere... Without storing the generated picture to a server's file system, there is no way for it (using a normal URL) to be able to serve it.

Since you are using the SRC attribute to store the canvas, you could use that string (usually long and unreadable) as the URL, but it will not point to any server or domain. The SRC of the image is actually the data of the image stored directly instead of being stored in a file.

To do so, get get image src and make the link point to it:

//html whose image will be created.
<div id="mydiv">
     <p>text!</p>
     <h1>This is a test!!</h1>
</div>

//div where image will be rendered.
<div id="image">
        <p>Image:</p>
</div>
<a href="#" id="image_link">Link to image</a>

//script to create image of html

<script type="text/javascript" src="/js/html2canvas.js"></script>
<script type="text/javascript">
    html2canvas([document.getElementById('mydiv')], {
        onrendered: function (canvas) {

            var data = canvas.toDataURL('image/gif');
            var image = new Image();
            image.src = data;
            document.getElementById('image').appendChild(image);
            document.getElementById('image_link').href = data; //Here

        }
    });
</script>

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