使用画布调整图像大小而不失真
Resize Image without Distortion using Canvas
我正在尝试加载存储在画布内的本地计算机中的图像文件。我可以在画布中加载图像,但如果图像的宽度或高度非常大,图像就会失真。我想使用画布将图像大小调整为 300 x 300 的尺寸,而不会扭曲图像,无论其大小如何。我尝试了很长时间,但无法弄清楚我哪里出错了。请帮忙..
网页代码..
<input type="file" id="ifile">
<canvas id="panel"></canvas>
JS代码..
//beginning of image display
canvasCtx = document.getElementById("panel").getContext("2d");
document.getElementById("ifile").onchange = function(event) {
this.imageFile = event.target.files[0];
var reader = new FileReader();
reader.onload = function(event) {
var img = new Image();
//img.style.width = "300px";
//img.style.height = "300px";
img.onload = function() {
drawImage(img);
}
img.src = event.target.result;
}
reader.readAsDataURL(this.imageFile);
}
drawImage = function(img) {
this.canvasCtx.canvas.width = 300;//img.width;
this.canvasCtx.canvas.height = 300;//img.height;
this.canvasCtx.drawImage(img,0,0,300,300);
url = canvasCtx.canvas.toDataURL();
console.log(url);
}
//end of image display
下面也给出了JS小提琴的链接...
JS小提琴
像下面这样更改drawImage
函数。我已经在上面声明了一个全局变量canvas
。
drawImage = function(img) {
// if else to keep aspect ratio in 300X300
if(img.width>img.height){
canvas.width = 300;
canvas.height = 300 / img.width * img.height;
} else {
canvas.width = 300 / img.height * img.width;
canvas.height = 300;
}
this.canvasCtx.drawImage(img, 0, 0, canvas.width, canvas.height);
url = canvasCtx.canvas.toDataURL();
}
更新的小提琴
相关文章:
- 如何使用url加载程序在webpack中导入多个图像
- nodejs-expressjs上传图像并显示它们
- 使用JSP从服务器检索和显示图像
- 角度:在ng重复上切换图像
- 画廊图像未显示
- Phonegap-(安卓/iphone)多个图像的图像库出现问题
- Javascript排序的图像弹出窗口..可以't单独弹出
- 画布数据到图像
- Windows8应用程序(html&Javascript):从图片库(除了文件选择器)显示图像的另一种方式
- 使图像在单击时展开到不大于浏览器
- Html页面上的多个Base64图像和平滑加载
- UIAutomation放大图像
- 使用javascript在Flash中加载外部图像
- 可以在这里为背景图像设置滤镜吗
- 当图像转换为本地存储的DataURL时,EXIF被删除
- Phonegap启动屏幕图像失真
- 使用画布调整图像大小而不失真
- 显示上传的图像,并将其缩放以适合图像字段而不失真
- JavaScript中的图像失真算法
- 使用fabricjs在Canvas中使图像失真和模糊