FabricJS对象不相对于画布大小调整 [英] FabricJS objects not relative to canvas resize

查看:1186
本文介绍了FabricJS对象不相对于画布大小调整的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用FabricJS创建全屏幕画布并保存更改服务器。在加载它之前,我调整画布&背景,以便在每个页面加载画布适合用户窗口内。

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?

推荐答案

经过很多尝试后,我发现一个解决方案感谢AndreaBogazzi的提示。当更改背景/画布大小/位置时,对象不会保持相对于背景/画布的大小/位置。

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.

这就是为什么最好使用缩放功能,这样所有的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;
    }
}

这将导致画布总是最大大小没有断裂比,不离开屏幕,所有元素保持正确的位置和高度。

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.

这篇关于FabricJS对象不相对于画布大小调整的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆