RPW RPW - 1 year ago 198
Javascript Question

fabric.js: How do I horizontally center fabric.Canvas() in the browser window?

I want to use

so I convert canvas to be
. 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
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

<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>
<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>

Answer Source

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>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download