FabricJS - 下载具有指定宽度和动态高度的图像

FabricJS - Download image with a specified width and dynamic height

我在 HTML Canvas 图像制作项目中使用 FabricJS。

我正在尝试弄清楚如何导出具有指定宽度但具有动态高度的图像。用户在 canvas 中创建的图像可以具有不同的高度,但始终保持相同的宽度 (1080px)。

我希望下载功能如下:

function saveImage(e) {
this.href = canvas.toDataURL({
format: "png",
quality: 0.8,
width: 1080,
height: auto
});
this.download = new Date().getTime() + ".png";
}
}

不幸的是,“height: auto”在这种情况下不起作用。我怎样才能达到我想要的结果?

这应该可以做到。想法是将当前 canvas 高度乘以导出宽度与当前宽度的比率,然后对其进行四舍五入以确保您的导出高度是整数。

function saveImage(e) {
    this.href = canvas.toDataURL({
        format: "png",
        quality: 0.8,
        width: 1080,
        height: Math.round(1080 / canvas.width * canvas.height)
    });
    this.download = new Date().getTime() + ".png";
}