I have a Canvas Object with top and left attributes defined through with a previous JavaScript function but when I create a fabric Canvas object
var fabricCanvas= new fabric.Canvas('mycanvas');
my HTML Canvas has top and left attributes set on 0.
I have tried setting the top and left attributes after the creation of fabric Canvas object through a script but when I do this the canvas changes position but the fabric function (selection and moving functions) remain where the canvas was located previously (where fabric Canvas has positioned it)!
What can I do to resolve this conflict? Is there a way to keep equal the canvas?
I have a Canvas Object with top and left attributes defined through with a previous JavaScript function but when I create a fabric Canvas object
var fabricCanvas= new fabric.Canvas('mycanvas');
my HTML Canvas has top and left attributes set on 0.
I have tried setting the top and left attributes after the creation of fabric Canvas object through a script but when I do this the canvas changes position but the fabric function (selection and moving functions) remain where the canvas was located previously (where fabric Canvas has positioned it)!
What can I do to resolve this conflict? Is there a way to keep equal the canvas?
Share Improve this question edited Nov 25, 2013 at 11:01 kangax 39.2k13 gold badges100 silver badges135 bronze badges asked Feb 13, 2012 at 14:08 JBerta93JBerta93 7193 gold badges16 silver badges28 bronze badges5 Answers
Reset to default 5When you create a canvas with Fabric.js it wraps it in a div and adds a second <canvas>
(used to select the objects rendered in the first canvas). This is explained in the wiki page of Fabric.js. If you want to position your canvas apply CSS rules to the parent div element which is of the class "canvas-container".
answer from my identical thread
apply
margin: 0 auto;
to class = canvas-container
canvas-container is automatically created by fabric.
see fiddle
Please notice that if your using some kind of css preprocessor (for me it was scss stylesheet inside Angular) - targeting the "canvas-container" class inside the ponent scss file will not work. For me the workaround was the general project css file.
You may override the canvas-container class upon initialization like so:
new fabric.Canvas('canvasId', {containerClass: 'custom-container-class'});
http://fabricjs./docs/fabric.Canvas.html#containerClass
I was able to override the style of the canvas-container by setting the element style after DOM was loaded.
HTML
<canvas id="canvas"></canvas>
JAVASCPRIT
const fabricCanvas = new fabric.Canvas("canvas", { containerClass: "myFabricCanvas"})
document.addEventListener('DOMContentLoaded', async function () {
document.getElementsByClassName('myFabricCanvas')[0].style.position="absolute"
document.getElementsByClassName('myFabricCanvas')[0].style.top=0
document.getElementsByClassName('myFabricCanvas')[0].style.left=0
});