在Fabric.js中全屏显示画布。

4
我希望我的canvas元素始终保持相同的大小——与客户端屏幕分辨率无关。
如果用户使用浏览器缩放,canvas元素应始终具有相同的大小。
此外,纵横比应始终相同——我想要一个1920-1080点的坐标空间。(如果浏览器没有相同的比例,则可以在canvas元素的一侧设置边框)。
我已经用html + css实现了这个问题:
  • 宽度为屏幕的100%
  • 最大坐标为1920 x 1080
但是当我使用fabric.js时,它改变了canvas的大小。 我无法将其设置回来,以实现响应式设计。
如何使用fabric.js实现这一点?
2个回答

5

经过一些尝试,我终于找到了一个只需修改css属性的解决方案。

答案非常简单,尽管很长。

这是我的html-body:

<body onload='init()'>
    <div id="canvasWrapper">
    <canvas id="canvas" width="100px" height="100px"></canvas>
</div>
</body>

这是我的CSS代码:
*{
    padding: 0;
    margin: 0;
    border: 0;
}

body{
    overflow: hidden;
}

#canvasWrapper {
    background-color: red;
    display: inline-block;
}

重要的部分是我的canvas-wrapper的“inline-block”和body元素的“overflow: hidden”。似乎在画布下方有一些像素,这会使两个滚动条出现。
经过一些实验,我得到了以下的js代码:
function init(){    
    resizeCanvas();         //resize the canvas-Element
    window.onresize = function()  { resizeCanvas(); }
}

每当屏幕尺寸发生变化时,我的“resize”函数将被调用。
整个技巧都在这个“resize”函数中完成:
function resizeCanvas() {
    var w = window,
        d = document,
        e = d.documentElement,
        g = d.getElementsByTagName('body')[0],
        x = w.innerWidth || e.clientWidth || g.clientWidth,
        y = w.innerHeight|| e.clientHeight|| g.clientHeight;

    var cv = document.getElementsByTagName("canvas")[0];
    //var cc = document.getElementsByClassName("canvas-container")[0];      //In case of non-Static Canvas will be used
    var cc = document.getElementById("canvasWrapper");

    var cx,cy;                  //The size of the canvas-Element
    var cleft=0;                //Offset to the left border (to center the canvas-element, if there are borders on the left&right)
    if(x/y > sizeX/sizeY){      //x-diff > y-diff   ==> black borders left&right
        cx = (y*sizeX/sizeY);
        cy = y;
        cleft = (x-cx)/2;
    }else{                      //y-diff > x-diff   ==> black borders top&bottom
        cx = x;
        cy = (x*sizeY/sizeX);
    }
    cc.setAttribute("style", "width:"+x+"px;height:"+y+"px;");                                          //canvas-content = fullscreen
    cv.setAttribute("style", "width:"+cx+"px;height:"+cy+"px;position: relative; left:"+cleft+"px");    //canvas: 16:9, as big as possible, horizintally centered
}

这个函数计算窗口宽度和最大画布大小,而不改变比例。

之后,我将包装器div设置为全屏大小,将canvas元素的大小设置为先前计算出的大小。

一切都可以在不更改canvas元素内容和不重绘任何内容的情况下正常工作。

它是跨浏览器兼容的(已在Firefox 25、Chrome 31和Internet Explorer 11上进行了测试)


在语句if(x/y > sizeX/sizeY)中,sizeX和sizeY是什么? 我是Canvas的新手。 - Salil Momin
@SalilMomin 这是两个全局变量,我从配置文件中加载它们。它们代表画布大小(画布内的坐标系大小,而不是屏幕上的实际像素大小)。我将它们设置为 var sizeX = 1920, sizeY = 1080; - maja
因此,sizeX/sizeY 是我想要实现的比例。在我的情况下是 16:9 - maja

4

版本2.4.2-b中的解决方案,它是官方API方法:http://fabricjs.com/docs/fabric.js.html#line7130

在我的代码中有效,将宽度和高度设置为100%:

fabricCanvas.setDimensions({
  width: '100%',
  height: '100%'
},{
  cssOnly: true
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接