Skip to content

Instantly share code, notes, and snippets.

Created January 22, 2018 12:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save anonymous/dcf4440371c6a26e64c30f39f04b8861 to your computer and use it in GitHub Desktop.
Save anonymous/dcf4440371c6a26e64c30f39f04b8861 to your computer and use it in GitHub Desktop.
FileAPIで画像読み込み & canvasに描画
<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