【发布时间】:2017-06-25 12:37:57
【问题描述】:
感谢您的观看。
我在这里要做的是...从计算机加载图像(通过使用 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 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);
}
问题是当我加载另一个图像文件时。它加载到画布中,但不适合画布大小。它保持原始图像大小,并且图像的“部分”显示在画布中。
为了解决这个问题,我尝试了以下方法:
ctx.drawImage(img, 0, 0, document.getElementById('canvas').width,
document.getElementById('canvas').height);
它可以工作,但是图像质量变得非常糟糕......因为它不是原始图像大小。它被调整到一定的高度并强制调整大小。
我想要做的就是...保持原来的画布大小(宽度:一些像素;高度:自动),所以当我加载图像时,它适合画布宽度和调整高度。
你能帮帮我吗?谢谢。
添加我自己研究了一下,发现如下: 我想出了一个主意——首先根据画布的当前宽度更改图像大小。
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。但是画布的高度不知何故变成了150px。我检查了,根本没有 css 应用到画布上。
所以这一次,我在 drawImage() 之前设置了画布宽度。
ctx.canvas.width = img.width;
ctx.canvas.height = img.height;
ctx.filter = window.getComputedStyle(img).filter;
ctx.drawImage(img, 0, 0);
再一次,原始图像返回......并且图像的“部分”显示在画布中。画布的大小是我想要的...
【问题讨论】:
-
请尝试创建一个有效的演示(目前它遗漏了一些重要的部分,例如您的 HTML 和 CSS)。
标签: javascript css html canvas