-
-
Save s-yoshiki/4e561b5a704f1dbda02e75e59e99065a to your computer and use it in GitHub Desktop.
FileAPIで画像読み込み & canvasに描画
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
<body> | |
<input type="file" id="file"> | |
<canvas id="canvas"></canvas> | |
<script> | |
document.getElementById("file").addEventListener("change", function (e) { | |
var file = e.target.files; | |
var reader = new FileReader(); | |
//ファイルが複数読み込まれた際に、1つめを選択 | |
reader.readAsDataURL(file[0]); | |
//ファイルが読み込めたら | |
reader.onload = function () { | |
var src = reader.result; | |
drawCanvas(src); | |
}; | |
}, false); | |
function drawCanvas(source) { | |
var canvas = document.getElementById('canvas'); | |
if (canvas.getContext) { | |
var context = canvas.getContext('2d'); | |
var image = new Image(); | |
image.src = source; | |
image.onload = function () { | |
canvas.width = image.width; | |
canvas.height = image.height; | |
context.drawImage(image, 0, 0); | |
}; | |
} | |
} | |
</script> | |
</body> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
解説記事
FileAPIで画像を読み込み → canvasに描画