我希望我的canvas-Element始终具有相同的大小 - 独立于客户端的屏幕分辨率。
如果用户使用浏览器进行缩放,则canvas元素应始终具有相同的大小。
此外,纵横比应始终相同 - 我想要一个1920-1080点的坐标空间。 (如果浏览器的比率不同,则canvas-element侧面可能有边框。)
我设法用html + css实现了这个:
但是当我发现fabric.js时,它改变了画布的大小。而我无法将其设置回来,以获得响应式设计。
我怎么能用fabric.js来实现这个目标?
答案 0 :(得分:5)
经过实验,我终于找到了一个解决方案,我只需要修改css-properties。
答案很简单,虽然时间很长。
这是我的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-element的“overflow:hidden”。似乎画布下面有一些像素,这会使两个滚动条出现。
经过一些实验,我得到了以下 js-code :
function init(){
resizeCanvas(); //resize the canvas-Element
window.onresize = function() { resizeCanvas(); }
}
每当屏幕尺寸发生变化时,我的“调整大小”功能将被调用。
整个技巧在这个resize-Function中完成:
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
}
此函数计算窗口宽度,以及可以在不改变比率的情况下实现的最大画布大小。
之后,我将wrapper-div设置为全屏大小,并将canvas-Element的大小设置为先前计算的大小。
一切正常,无需更改canvas元素的内容,也无需重绘任何内容。
它是跨浏览器兼容的(在Firefox 25,Chrome 31和Internet Explorer 11上测试)
答案 1 :(得分:1)
版本2.4.2-b中的解决方案,它是Api的官方方法:http://fabricjs.com/docs/fabric.js.html#line7130
它在我的代码中有效,将宽度和高度设置为100%:
fabricCanvas.setDimensions({
width: '100%',
height: '100%'
},{
cssOnly: true
});