简体   繁体   English

使用fabricjs在Canvas中图像变得失真和模糊

[英]Image gets distorted and blurry in Canvas using fabricjs

I am uploading an image and then displaying it in canvas using fabricjs. 我正在上传图像,然后使用fabricjs在画布上显示它。 Uploaded image is fine. 上传的图片很好。 But when I load it in canvas its distorted and blurry. 但是,当我将其加载到画布中时,其变形和模糊。 Here is the code I am using to load image in canvas. 这是我用来在画布中加载图像的代码。

$("#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);
});

Also it resizes the square image (image width == image height) into rectangular shaped image. 此外,它将正方形图像(图像宽度==图像高度)调整为矩形图像。

Any help will be much appreciated. 任何帮助都感激不尽。 Thanks 谢谢

Your code sets in the third if : if以下条件,您的代码将排在第三位:

if (img.height == img.width) {
    img.height = 100;
    img.width = 200;
}

so any square (1:1) image is distorted to be a 2:1 image. 因此任何正方形(1:1)图像都会失真为2:1图像。

I'd write the resizing like this: 我会这样写调整大小:

if (img.height > img.width) {
    img.scaleToHeight(80);
}
if (img.height <= img.width) { //include square images here
    img.scaleToWidth(120);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM