Multiple canvases (pages) in Fabric.js

╄→尐↘猪︶ㄣ 提交于 2019-12-23 03:58:12

问题


I am trying to create multiple pages as canvases using Fabric.js on click of a button - e.g. every time the button is clicked a new page is created.

The problem I'm having is that I want these canvases to use the same functions which are created at when the page is loaded and are only assigned to the initial canvas. Is there a way to create instances of the canvas and still use those same functions?


回答1:


My understanding of your question is that you are creating multiple canvases within a single HTML document.

When you are assigning functions to your initial canvas, do you mean they are being added as methods to your canvas object? I think it is better to wrap the canvas in another JavaScript object and assign methods to that object. Also, you can use prototype to define methods for a class, then these methods will be accessible by instances of that class. For example:

/* MyCanvas class */
function MyCanvas() {
    /* Creates a canvas */
    this.canvas = document.createElement("canvas");
    document.body.appendChild(this.canvas);
};

/* Define MyCanvas prototype */
MyCanvas.prototype = {
    /* Define getCanvas method */
    getCanvas: function() {
        /* Returns the real canvas object */
        return this.canvas;
    },

    /* Define get2DContext method */
    get2DContext: function() {
        /* Returns the 2D context */
        return this.canvas.getContext("2d");
    }
}

/* Create two canvases */
var myCanvas1 = new MyCanvas();
var myCanvas2 = new MyCanvas();

/* Access MyCanvas methods */
var canvas1 = myCanvas1.getCanvas();
var ctx2 = myCanvas2.get2DContext();

By the way, I've never used fabric.js.



来源:https://stackoverflow.com/questions/20276861/multiple-canvases-pages-in-fabric-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!