我想使用fabric.js
,因此我将canvas转换为fabric.Canvas
。但是,这会使画布向左而不是居中(使用fabric.js v1.6.6
和任何现代浏览器,例如Safari,Firefox,Chrome)。如何在浏览器窗口中水平居中fabric.Canvas
?
var canvas = new fabric.Canvas('c');
var triangle = new fabric.Triangle({
width: 40,
height: 50,
fill: 'blue',
left: 50,
top: 50
});
canvas.add(triangle);
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.6.7/fabric.min.js"></script>
<div id="fabric_div" style="text-align:center">
<canvas id="c" width="400" height="250" style="border:1px solid #ff0000"></canvas>
</div>
<p>Above is the fabric.canvas, and it appears flush left in the browser window.</p>
<p>Below is the regular canvas, and it appears centred horizontally in the browser window.</p>
<div id="regular_div" style="text-align:center">
<canvas id="d" width="400" height="250" style="border:1px solid #00ff00"></canvas>
</div>
答案 0 :(得分:3)
由于您已经拥有固定的对象宽度,因此可以将margin: 0 auto;
添加到css中的.canvas-container
,如下所示:
<style>.canvas-container{margin: 0 auto;}</style>
var canvas = new fabric.Canvas('c');
var triangle = new fabric.Triangle({
width: 40,
height: 50,
fill: 'blue',
left: 50,
top: 50
});
canvas.add(triangle);
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.6.7/fabric.min.js"></script>
<style>
.canvas-container {
margin: 0 auto;
}
</style>
<div id="fabric_div" style="text-align:center">
<canvas id="c" width="400" height="250" style="border:1px solid #ff0000"></canvas>
</div>
<p>Above is the fabric.canvas, and it appears flush left in the browser window.</p>
<p>Below is the regular canvas, and it appears centred horizontally in the browser window.</p>
<div id="regular_div" style="text-align:center">
<canvas id="d" width="400" height="250" style="border:1px solid #00ff00"></canvas>
</div>