Created
August 27, 2020 20:40
-
-
Save yswallow/fa9258699ed88f0a8dde4e59097ff957 to your computer and use it in GitHub Desktop.
選択したファイルをCanvasとimgでプレビューするスクリプト
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <html> | |
| <body> | |
| <canvas id="draw-area" width="480" height="320"></canvas> | |
| <input id="select-image" type="file" accept="image/*"> | |
| <div id="filename"></div> | |
| <img id="imagePreview"> | |
| <script> | |
| drawingArea = document.getElementById("draw-area"); | |
| imageSelection = document.getElementById("select-image"); | |
| filenameOutput = document.getElementById("filename"); | |
| imagePreview = document.getElementById("imagePreview"); | |
| if(window.FileReader && window.Image) { | |
| reader = new FileReader(); | |
| reader.addEventListener("load", (fileReaderEvent)=>{ | |
| console.log(fileReaderEvent); | |
| imagePreview.src = fileReaderEvent.target.result; | |
| image.src = fileReaderEvent.target.result; | |
| }); | |
| const image = new Image(); | |
| image.addEventListener("load", ()=>{ | |
| zoom = 480 / image.naturalWidth; | |
| drawingArea.height = image.naturalHeight * zoom; | |
| ctx = drawingArea.getContext("2d"); | |
| ctx.scale(zoom,zoom); | |
| ctx.drawImage(image, 0, 0); | |
| ctx.scale(1,1); | |
| }); | |
| imageSelection.addEventListener("change", (e)=>{ | |
| filenameOutput.innerText = e.target.value; | |
| file = e.target.files[0]; | |
| reader.readAsDataURL(file); | |
| }); | |
| } | |
| </script> | |
| <style> | |
| canvas#draw-area { | |
| border: solid 3px; | |
| } | |
| </style> | |
| </body> | |
| </html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment