Javascript HTML 5画布]调整大小时的图像质量
谢谢你看 我在这里想做的是。。。从计算机加载图像(使用FileReader),将img标记的src放入文件。然后用这个图像画画布Javascript HTML 5画布]调整大小时的图像质量,javascript,css,html,canvas,Javascript,Css,Html,Canvas,谢谢你看 我在这里想做的是。。。从计算机加载图像(使用FileReader),将img标记的src放入文件。然后用这个图像画画布 function previewFile(){ var preview = document.querySelector('img'); //selects the query named img var file = document.querySelector('input[type=file]').files[0]; //sames as he
function previewFile(){
var preview = document.querySelector('img'); //selects the query named img
var file = document.querySelector('input[type=file]').files[0]; //sames as here
var reader = new FileReader();
reader.onload = function () {
preview.src = reader.result;
drawCanvas();
}
if (file) {
reader.readAsDataURL(file); //reads the data as a URL
} else {
preview.src = "sample.jpg";
}
}
previewFile(); //calls the function named previewFile
window.onload = function () {drawCanvas(); };
function drawCanvas() {
var img = document.querySelector("img");
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext('2d');
ctx.filter = window.getComputedStyle(document.querySelector("img")).filter;
ctx.drawImage(img, 0, 0);
}
问题是当我加载另一个图像文件时。它在画布中加载,但不适合画布大小。它保持原始图像大小,图像的“部分”显示在画布中
var img = document.querySelector("img");
var canvas = document.getElementById("image");
var ratio = img.height / img.width;
img.width = canvas.offsetWidth;
img.height = img.width * ratio;
为了解决这个问题,我尝试了以下方法:
ctx.drawImage(img,0,0,document.getElementById('canvas')。宽度,document.getElementById('canvas')。高度) 它可以工作,但是图像质量变得很差。。。因为它不是原始图像的大小。将其调整到特定高度并强制调整大小 我想做的就是。。。保持原始画布大小(宽度:some px;高度:auto),因此当我加载图像时,它适合画布宽度和调整后的高度 你能帮帮我吗?多谢各位 补充 我研究了自己,发现如下: 我想出了一个主意——首先根据画布的当前宽度更改图像大小
var img = document.querySelector("img");
var canvas = document.getElementById("image");
var ratio = img.height / img.width;
img.width = canvas.offsetWidth;
img.height = img.width * ratio;
然后用编辑后的图像进行绘制
var ctx = canvas.getContext('2d');
ctx.filter = window.getComputedStyle(img).filter;
ctx.drawImage(img, 0, 0, img.width, img.height);
然后我发现了问题。我检查了“img.height”变量是199px。但画布的高度不知怎的变成了150像素。我检查了一下,没有css应用到画布上
所以这次,我在drawImage()之前设置画布宽度
再一次,原始图像回来了。。。图像的“部分”显示在画布中。画布的大小正是我想要的…非常感谢您关注这个问题。尤其是试图帮忙的@kaido。非常感谢。我真的是个新手。。。所以我不知道如何创建演示 我找到了解决办法。好这确实是画布的基本知识,但我认为很多人会忘记/错过以下内容:
var ctx = canvas.getContext('2d');
ctx.canvas.width = 1000;
ctx.canvas.height = 1000;
ctx.drawImage(img, 0, 0, 800, 800);
ctx.canvas.width是画布的宽度。ctx.canvas.height是画布的高度。
在drawImage中,这些800是将绘制的图像的宽度和高度,而不是画布的大小!!所以如果你设定。。。比如说1000,1000在drawImage中,图像的大小将被调整到画布中。如果大于画布大小,则只显示图像的“部分”
所以我所做的是。。。获取要放置画布的div宽度大小。然后首先计算图像的比率(比率=图像的高度/宽度)。然后将画布大小设置为以下值(ctx.canvas.width=div width size,ctx.canvas.height=div width size*ratio)。然后用canva的宽度和高度(ctx.drawImage(img,0,0,ctx.canvas.width,ctx.canvas.height))绘制画布
希望这对像我这样的新人有所帮助:)谢谢。可能重复的请尝试创建一个工作演示(目前它遗漏了一些重要部分,如HTML和CSS)。@Alejandro González我两天内无法接受我自己的答案:(