Reputation: 2680
I am working on a project that requires creating multiple canvas elements (separate bars each representing one distinct gradient). I would like to do this dynamically with fabric.js, eg:
function add_gradient(color_stops){
// Add a new rectangular canvas with fill representing specified gradient
var grad_box = document.getElementById("divWithCanvases");
var newCanvas = document.createElement("canvas");
grad_box.appendChild(newCanvas);
var gradCanvas = fabric.Canvas(newCanvas, {width: 500, height:50});
var ctx = gradCanvas.getContext('2d');
// Do stuff to canvas...
}
However, the call to fabric.Canvas
fails with an error "this.initialize is undefined". (fabric.js line 1627, version 1.4.13)
How can I either:
appendChild
)According to the fabric.js documentation, the fabric.Canvas
constructor accepts either an HTMLElement, or a string element id. I can only make it work with the string.
Upvotes: 6
Views: 9329
Reputation: 857
You can create canvas element from the fabric utility itself via createCanvasElement
and then assign this newly created elemment as first parameter of Canvas constructor function to create virtual canvas and still have the ability to perform operations.
let tempCanvasEl = fabric.util.createCanvasElement(),
tempCanvasCtx = tempCanvasEl.getContext('2d',{ willReadFrequently: true }),
tempCanvas = new fabric.Canvas(tempCanvasEl)
or even use staticCanvas
constructor in case if the new canvas is only for read operations like getPixelColor for example as willReadFrequently
is true here.
tempCanvas = new fabric.StaticCanvas(tempCanvasEl)
Hope this helps.
Upvotes: 0
Reputation: 3730
When we want to add canvas dynamically and want to call canvas fabric API then we need to give a different name like this..
var html_canvas = document.createElement('canvas');
html_canvas.id = "CursorLayer";
var canvas = new fabric.Canvas(html_canvas, canvasConfigOptions);
// canvasConfigOptions is optional
Now we can perform all fabric operations on this canvas
Upvotes: 0
Reputation: 614
I was getting the above error because of <div id="canvas"> </div>
Make sure your html element should be canvas
<canvas id="canvas"> </canvas>
Upvotes: 0
Reputation: 62466
The function fabric.Canvas is a constructor, you have to call it with the new operator:
var gradCanvas = new fabric.Canvas(newCanvas, {width: 500, height:50});
Upvotes: 5