FabricJS objects not relative to canvas resize

假如想象 提交于 2019-12-05 07:59:57

问题


I'm using FabricJS to create a fullscreen canvas and save the changes serverside. 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?


回答1:


After a lot of trying I found a solution thanks to a hint from 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.



来源:https://stackoverflow.com/questions/34874844/fabricjs-objects-not-relative-to-canvas-resize

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!