I am unable to load json into fabric.js (via canvas.loadFromJSON
) and then create a TextBox
which I add to the canvas. The image shows, but the TextBox
does not show.
I believe the issue might be because I’m loading a type image
. In the examples on fabricjs.com, it shows loading rect
or circle
. Or, whilst this is a difference, there is something else that is wrong entirely.
I’ve created some code that demonstrates this.
https://jsfiddle.net/cbp612wo/1/
<canvas id="c" width="600" height="600"></canvas>
<script>
let canvas = new fabric.Canvas('c');
const jsonWithShape = JSON.stringify({"objects":[{"type":"rect","originX":"center","originY":"center","left":300,"top":150,"width":150,"height":150,"fill":"#29477F","overlayFill":null,"stroke":null,"strokeWidth":1,"strokeDashArray":null,"strokeLineCap":"butt","strokeLineJoin":"miter","strokeMiterLimit":10,"scaleX":1,"scaleY":1,"angle":0,"flipX":false,"flipY":false,"opacity":1,"shadow":{"color":"rgba(94, 128, 191, 0.5)","blur":5,"offsetX":10,"offsetY":10},"visible":true,"clipTo":null,"rx":0,"ry":0,"x":0,"y":0}]});
const jsonWithImage = JSON.stringify({"objects":
[{
"type": "image",
"version": "5.2.1",
"originX": "left",
"originY": "top",
"left": 0,
"top": 0,
"width": 0,
"height": 0,
"fill": "rgb(0,0,0)",
"stroke": null,
"strokeWidth": 0,
"strokeDashArray": null,
"strokeLineCap": "butt",
"strokeDashOffset": 0,
"strokeLineJoin": "miter",
"strokeUniform": false,
"strokeMiterLimit": 4,
"scaleX": 1,
"scaleY": 1,
"angle": 0,
"flipX": false,
"flipY": false,
"opacity": 1,
"shadow": null,
"visible": true,
"backgroundColor": "",
"fillRule": "nonzero",
"paintFirst": "fill",
"globalCompositeOperation": "source-over",
"skewX": 0,
"skewY": 0,
"cropX": 0,
"cropY": 0,
"src": "https://stackoverflow.design/assets/img/logos/so/logo-screen.svg",
"crossOrigin": null,
"filters": []
}]
});
//Uncomment one or the other of the lines 2 lines below - the text only shows on the shape (rect)
//canvas.loadFromJSON(jsonWithShape); //this works as expected
canvas.loadFromJSON(jsonWithImage); //this does not show the text
const txt = "Hello world";
const t1 = new fabric.Textbox(txt, {
textAlign: 'center'
});
canvas.add(t1);
canvas.renderAll.bind(canvas)
</script>
In the example above, I’ve commented out one of the lines so you can essentially toggle between a working example (by commenting/uncommenting where specified)
What am I doing wrong? Why can’t I see text and the SO logo?