JSFiddle - React, Tailwind, and code Playground
by ahomu
HTML
<canvas id="canvas"></canvas>
<form aciton="" method="post">
<input id="input" type="file" name="testinput" value="">
</form>
JavaScript
var input = document.getElementById('input'),
canvas = document.getElementById('canvas'),
_image = document.createElement('image'),
reader = new FileReader();
// 読み込んだときの動作
reader.onload = function() {
// 大きい画像を_image.srcにresultで入れた後,
// ノンタイムでdrawImageに渡すと描画されないためloadを待つ
_image.onload = function() {
// てきとーにwidthが800以上なら0.3倍にスケール
var ratio = (_image.width > 800) ? 0.3 : 1,
ctx = canvas.getContext('2d');
canvas.width = _image.width * ratio;
canvas.height = _image.height * ratio;
ctx.scale(ratio, ratio);
ctx.drawImage(_image, 0, 0);
};
_image.src = reader.result;
};
input.addEventListener('change', function(e) {
// ここではmultiple属性は考慮しない
var file = this.files[0];
// MIMEタイプが画像系のモノのみ
if ( file.type.indexOf('image') === -1 ) {
return;
}
// 画像プレビューを扱えるようにデータURLで読み込む
reader.readAsDataURL(file);
});