当前位置:   article > 正文

JavaScript - canvas - 将图片保存到本地_js保存canvas图片到本地

js保存canvas图片到本地

效果

在这里插入图片描述

示例

项目结构

在这里插入图片描述

源码:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>将图片保存到本地</title>
    </head>
    <body>
        <canvas id="canvas"></canvas>
        <br />
        <input type="button" id="button-save-as" value="Save as..." />

        <script type="text/javascript">
            window.onload = function(event) {
                main();
            }
            
            function main() {
                const canvas = document.querySelector("#canvas");
                const canvasContext = canvas.getContext("2d");
                
                {
                    // 先在 canvas 上面画一张图片
                    const image = new Image();
                    image.onload = (event) => {
                        // console.log(event);
                        canvas.width = image.width;
                        canvas.height = image.height;
                        canvasContext.drawImage(image, 0, 0);
                    }
                    image.src = "img/transformers.jpg";
                }
                
                {
                    const buttonSaveAs = document.getElementById('button-save-as');
                    buttonSaveAs.onclick = (event) => {
                        canvas.toBlob(function (blob) {
                            // https://developer.mozilla.org/en-US/docs/Web/API/Blob/Blob
                            const objectURL = URL.createObjectURL(new Blob([ blob ], { type: "image/png" }));
                            
                            const anchor = document.createElement('a');
                            anchor.href = objectURL;
                            anchor.download = "Filename.png";
                            
                            anchor.click();
                            
                            URL.revokeObjectURL(objectURL);
                        }, "image/png", 1);
                    };
                }
            }
        </script>
    </body>
</html>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/229342
推荐阅读
相关标签
  

闽ICP备14008679号