我正在上传图片,然后使用fabricjs在画布中显示它。上传的图片很好。但是当我在画布中加载它时,它变形和模糊。 这是我用来在画布中加载图像的代码。
$("#canvas_area").append('<canvas id="c"></canvas>');
var canvas = new fabric.Canvas('c');
canvas.setDimensions({
width: '100%',
height: '100%'
}, {
cssOnly: true
});
var imgElement = response.uploaded_file;
fabric.Image.fromURL(imgElement, function (img) {
img.set({
borderColor: 'red',
cornerColor: 'green',
cornerSize: 6,
transparentCorners: false
});
if (img.height > img.width) {
img.scaleToHeight(80);
}
if (img.height < img.width) {
img.scaleToWidth(120);
}
if (img.height == img.width) {
img.height = 100;
img.width = 200;
}
img.set('left', 10);
img.set('top', 10);
img.setCoords();
canvas.add(img);
});
它还将方形图像(图像宽度==图像高度)调整为矩形图像。
任何帮助将不胜感激。感谢
答案 0 :(得分:2)
您的代码设置在第三个if
:
if (img.height == img.width) {
img.height = 100;
img.width = 200;
}
因此任何方形(1:1)图像都会失真为2:1图像。
我写这样的大小调整:
if (img.height > img.width) {
img.scaleToHeight(80);
}
if (img.height <= img.width) { //include square images here
img.scaleToWidth(120);
}