最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - FabricJS objects not relative to canvas resize - Stack Overflow

programmeradmin3浏览0评论

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?

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?

Share Improve this question asked Jan 19, 2016 at 10:50 SamSam 1,3433 gold badges24 silver badges41 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 8

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.

发布评论

评论列表(0)

  1. 暂无评论