JavaScript - canvas - 通过 <input type=“file“ /> 加载图片

文章目录

  • 参考

JavaScript - canvas - 通过 <input type=“file“ /> 加载图片_第1张图片

DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Using imagetitle>
        <style type="text/css">
            * {
                /* margin: 0;
                padding: 0; */
                box-sizing: border-box;
            }
            canvas {
                border-width: 1px;
                border-color: #000000;
                border-style: solid;
            }
        style>
    head>
    <body>
        <canvas id="canvas">canvas>
        
        <div>
            <input type="file" accept="image/*" />
        div>
        
        <script type="text/javascript">
            window.onload = (event) => {
                main()
            }
            
            function main() {
                const canvas = document.getElementById("canvas");
                const ctx = canvas.getContext("2d");
                
                const inputFile = document.querySelector("input[type=file]");
                inputFile.onchange = (event) => {
                    const files = event.target.files;
                    if (files.length > 0) {
                        const file = files[0]; // First file
                        console.log(file);
                        
                        const image = new Image();
                        image.src = URL.createObjectURL(file);
                        image.onload = function(event) {
                            // console.log(event, this);
                            URL.revokeObjectURL(this.src);
                            
                            canvas.width = image.width;
                            canvas.height = image.height;
                            
                            ctx.drawImage(image, 0, 0);
                        }
                    }
                }
            }
        script>
    body>
html>

参考

Web technology for developers > Web APIs > Canvas API > Canvas tutorial > Using images

你可能感兴趣的:(HTML,&,CSS,&,JavaScript,JavaScript,HTML,CSS,canvas)