JSFiddle - React, Tailwind, and code Playground
by KEN73CHEN
HTML
<label id="upload" for="id_image_large" class="btn btn-default choose-file">
拖曳相片到這或點選上傳
</label>
<span class='hidden'>
<input type="file" id="id_image_large"/>
<input type="hidden" name="photo_data" id='photo_data'/>
</span>
CSS
@import url("//netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css");
#upload {
width: 500px;
height: 150px;
margin:0 0;
text-align: center;
line-height: 140px;
background-repeat:no-repeat;
background-position: 10px 10px;
}
.btn-file label {
width: 100%;
height: 100%;
}
JavaScript
Object.append(Element.NativeEvents, {
dragenter: 2, dragleave: 2, dragover: 2, dragend: 2, drop: 2, dragstart: 2
});
window.addEvent('domready', initPage);
function initPage() {
document.id('upload').addEvents({
'dragover':function(e) {
e.preventDefault();
this.highlight();
},
'drop':function(e){
e.stop();
if (e.event.dataTransfer && e.event.dataTransfer.files.length >= 1) {
photoPreview(e.event.dataTransfer.files[0]);
}
}
});
document.id('id_image_large').addEvent('change',function(){
photoPreview(this.files[0]);
});
}
function photoPreview(file) {
if (!file) return false;
if (file.type.substr(0,6) !== 'image/') {
alert(file.name+' 不是圖片檔案');
return false;
}
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function(e) {
Asset.image(e.target.result, {
'onLoad': function() {
var max_w = 800, max_h = 600;
var image_w = this.width, image_h = this.height;
console.log("before resize: "+this.src.length);
if (image_w > max_w || image_h > max_h) {
var scale = Math.min(max_h / image_h, max_w/image_w);
var mainCanvas = document.createElement("canvas");
mainCanvas.width = image_w;
mainCanvas.height = image_h;
var ctx = mainCanvas.getContext("2d");
ctx.drawImage(this, 0, 0, mainCanvas.width, mainCanvas.height);
// resize to qualified photo and put it in input element
var canvas = document.createElement("canvas");
canvas.width = image_w * scale;
canvas.height = image_h * scale;
var ctx_resize = canvas.getContext("2d");
ctx_resize.drawImage(mainCanvas, 0, 0,...