canvas画图实现图片等比例展示,以及图片预览有时候不展示的原因
声明:我是在vue项目下写的;
1.用canvas画图,但是图片有时候出现有时候不出现的;
附上源代码:
<input type="file" accept="image/*" @change="showImage"/>
showImage(e) { let vm = this; let reader = null; if(window.FileReader) { reader = new FileReader; } else { alert('浏览器不支持预览功能'); } let imageFiles = e.target.files[0]; reader.readAsDataURL(imageFiles); reader.onload = function(event) { //reader.onload之后直接将图片写入 canvas,会出现图片有时候会没有显示 let img = new Image(); img.src = event.target.result; let canvas = document.getElementById('canvas'); let ctx = canvas.getContext('2d'); ctx.beginPath(); ctx.drawImage(img,0,0,300,300); ctx.closePath(); } },
修改方法为
showImage(e) { let vm = this; let reader = null; if(window.FileReader) { reader = new FileReader; } else { alert('浏览器不支持预览功能'); } let imageFiles = e.target.files[0]; reader.readAsDataURL(imageFiles);
reader.onload = function(event) { let img = new Image(); img.src = event.target.result; img.onload = function() { //等图片读取完成之后再写入canvas let canvas = document.getElementById('canvas'); let ctx = canvas.getContext('2d'); ctx.beginPath(); ctx.drawImage(img,0,0,300,300); ctx.closePath(); } } },
2.图片等比例展示
showImage(e) {
let vm = this;
let reader = null;
if(window.FileReader) {
reader = new FileReader;
} else {
alert('浏览器不支持预览功能');
}
let imageFiles = e.target.files[0];
reader.readAsDataURL(imageFiles);
reader.onload = function(event) {
let img = new Image();
img.src = event.target.result;
img.onload = function() { //等图片读取完成之后再写入canvas
let imgWidth = img.width/2;
let imgHeight = img.height/2;
let canvas = document.getElementById('canvas');
let scale = 1;
let tt = 400;
if(imgHeight > tt || imgWidth >tt) {
if(imgWidth > imgHeight) {
scale = tt/imgWidth/2;
}else {
scale = tt/imgHeight/2;
}
}
canvas.height = imgHeight*scale;
canvas.width = imgWidth*scale;
let ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.drawImage(img,0,0,canvas.width,canvas.height);
ctx.closePath();
}
}
},
showImage(e) {
let vm = this;
let reader = null;
if(window.FileReader) {
reader = new FileReader;
} else {
alert('浏览器不支持预览功能');
}
let imageFiles = e.target.files[0];
reader.readAsDataURL(imageFiles);
reader.onload = function(event) {
let img = new Image();
img.src = event.target.result;
img.onload = function() { //等图片读取完成之后再写入canvas
let imgWidth = img.width/2;
let imgHeight = img.height/2;
let canvas = document.getElementById('canvas');
let scale = 1;
let tt = 400;
if(imgHeight > tt || imgWidth >tt) {
if(imgWidth > imgHeight) {
scale = tt/imgWidth/2;
}else {
scale = tt/imgHeight/2;
}
}
canvas.height = imgHeight*scale;
canvas.width = imgWidth*scale;
let ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.drawImage(img,0,0,canvas.width,canvas.height);
ctx.closePath();
}
}
},