动态设置图像高度和宽度后,Fabric js 图像质量并没有变好

Fabric js image quality is not getting good after set image height and width dynamically

我已将图像添加到 canvas 中,并且我想根据矩形的高度和宽度动态更改图像的高度和宽度。我已经根据矩形的高宽和原图的高宽计算了图片的高宽

我使用下面的代码更改了图像的高度和宽度,但图像质量变得非常低

var image_height = 200; //For now here image height is dummy
var image_width = 150; //For now here image width is dummy
var obj = canvas.getActiveObject();
obj.setHeight(image_height);
obj.setWidth(image_width);
obj.setCoords();
canvas.renderAll();

我运行几天前遇到了同样的问题。我找到的解决方案是不要尝试设置 widthheight,而是让您的图像 缩放 到 canvas 尺寸。

我是这样做的:

var scaleWidth = canvas.getWidth() / img.width;
var scaleHeight = canvas.getHeight() / img.height;
var scale = Math.min(scaleWidth, scaleHeight);
bgImage = new fabric.Image(img, {
    [...]
    scaleX: scale,
    scaleY: scale,
    [...]
  });
canvas.add(bgImage);
canvas.sendToBack(bgImage); // useful in case you want a background but not **needed**
canvas.renderAll();

在上面的代码中,我计算了宽度和高度的比率,选择较低的那个,然后我使用 scaleXscaleY 属性将它应用到图片上。

如果还是不行,请在评论中告诉我。

编辑:为了更清楚起见,我完成了我的链接代码。

第二次编辑: 似乎存在一种名为 scale 的方法,可用于您的图像。如果你想保持你的比率看起来更干净(又名 scaleXscaleY 属性将具有相同的值)。

当你导出canvas到图像时,你可以添加乘数。它将增加分辨率以及图像的大小。

canvas.toDataURL({ multiplier: 8 });