简体   繁体   English

FabricJS对象与画布调整大小无关

[英]FabricJS objects not relative to canvas resize

I'm using FabricJS to create a fullscreen canvas and save the changes serverside. 我正在使用FabricJS创建全屏画布并在服务器端保存更改。 Before loading it I resize the canvas & background so that on every page-load the canvas fits inside the users window. 加载之前,我会调整画布和背景的大小,以便在每次加载页面时,画布都适合用户窗口。

canvas.setHeight($(window).height());
canvas.setWidth($(window).width());
canvas.backgroundImage.width = $(window).width();
canvas.backgroundImage.height = $(window).height();

The problem is that the canvas & background get adjusted but not the objects. 问题是调整画布和背景而不调整对象。 They keep the same position relative to the screen and don't change size so are incorrent on other screensizes. 它们相对于屏幕保持相同的位置,并且不会更改尺寸,因此与其他屏幕尺寸不一致。 How can this problem be solved? 如何解决这个问题?

After a lot of trying I found a solution thanks to a hint from AndreaBogazzi. 经过大量的尝试,由于AndreaBogazzi的提示,我找到了解决方案。 When changing the background/canvas size/position the objects do not keep there size/position relative to the background/canvas. 更改背景/画布尺寸/位置时,对象相对于背景/画布的尺寸/位置不会保持在那里。

That's why it's better to use the zoom functionality, this way all of the canvas elements gets adjusted the same way relative to each other: 这就是使用缩放功能更好的原因,这样所有画布元素之间的相对调整方式相同:

// background: background image
// zoom: zoom amount usable with canvas.setZoom(zoom).

if (background.width < $(window).width()) {
    zoom = $(window).height() / background.height;

    if ((zoom * background.width) > $(window).width()) {
        zoom = $(window).width() / background.width;
    }

} else {
    zoom = $(window).width() / background.width;

    if ((zoom * background.height) > $(window).height()) {
        zoom = $(window).height() / background.height;
    }
}
canvas.setZoom(zoom );

This will result in the canvas always being it's maximum size without breaking ratio, without leaving the screen and with all the elements keeping the right position and height. 这将导致画布始终是其最大尺寸而不会破坏比率,不会离开屏幕,并且所有元素都保持正确的位置和高度。

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

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