Created
January 22, 2018 12:46
-
-
Save anonymous/dcf4440371c6a26e64c30f39f04b8861 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> | |
//fileの読み込みイベント | |
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 source = reader.result; | |
//描画関数 | |
drawCanvas(); | |
}; | |
}, false); | |
//canvasに描画する | |
//@source : ファイル(画像)のURL | |
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