javascript 在fabric.js 中设置画布的宽度和高度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23373451/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
set width and height of canvas in fabric.js
提问by Jcbo
I have an image background in my HTML5 canvas.
我的 HTML5 画布中有一个图像背景。
var canvas = new fabric.Canvas('#canvas1');
canvas.setBackgroundImage(
'http://fabricjs.com/assets/jail_cell_bars.png',
canvas.renderAll.bind(canvas)
);
How to set dimensions of my canvas (width, height) to the dimensions of the background image?
如何将画布的尺寸(宽度、高度)设置为背景图像的尺寸?
Thanks.
谢谢。
采纳答案by midu
You can use CSS or dom properties to set the dimensions of your canvas. If you know the dimensions of your image, you can do it in a stylesheet:
您可以使用 CSS 或 dom 属性来设置画布的尺寸。如果您知道图像的尺寸,则可以在样式表中进行:
#canvas1 { width: XXXpx; height: YYYpx; }
Or in the dom:
或者在 dom 中:
<canvas id="canvas1" width="XXX" height="YYY"></canvas>
If the image is dynamic and want to set the dimensions in JS, you do something like this:
如果图像是动态的并且想在 JS 中设置尺寸,你可以这样做:
var image = new Image()
image.src = 'http://fabricjs.com/assets/jail_cell_bars.png';
image.onLoad = function () {
var canvas = document.getElementById('canvas1');
canvas.width = image.width;
canvas.height = image.height;
};
回答by Calvin
I think the above answer does not use fabric.js, it uses normal canvas.
我认为上面的答案不使用fabric.js,它使用普通画布。
When you use fabric.js and its Fabric.Canvas class, the code should be:
当你使用 fabric.js 和它的 Fabric.Canvas 类时,代码应该是:
image.onLoad = function() {
var fabric_canvas = new fabric.Canvas('canvas1');
fabric_canvas.setDimensions({width:image.width, height:image.height});
};
In my case,
就我而言,
var canvas = new fabric.Canvas("test_fabric");
canvas.setDimensions({width:800, height:200});
The result is:
结果是:
<canvas id="test_fabric" width="800" height="200" class="lower-canvas" style="position: absolute; width: 800px; height: 200px; left: 0px; top: 0px; -webkit-user-select: none;"></canvas>
Both canvas.width and canvas.style.width are set.
canvas.width 和 canvas.style.width 都已设置。