Reputation: 335
I want to use fabric.js
so I convert canvas to be fabric.Canvas
. However, this makes the canvas flush left rather than centered (using fabric.js v1.6.6
and any modern browser, e.g., Safari, Firefox, Chrome). How do I center a fabric.Canvas
horizontally in the browser's window?
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>
Upvotes: 0
Views: 1882
Reputation: 1086
as you already have a fixed width for the object you can add margin: 0 auto;
to the .canvas-container
in your css like this:
<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>
Upvotes: 3