问题描述
我试图在点击按钮时使用Fabric.js创建多个页面作为画布 - 例如每次单击按钮时都会创建一个新页面。
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?
推荐答案
我对你的问题的理解是你的在单个HTML文档中创建多个画布。
My understanding of your question is that you are creating multiple canvases within a single HTML document.
在为初始画布分配函数时,是否意味着将它们作为方法添加到画布对象中?我认为最好将画布包装在另一个JavaScript对象中并为该对象分配方法。此外,您可以使用prototype来定义类的方法,然后可以通过该类的实例访问这些方法。例如:
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();
顺便说一下,我从未使用过fabric.js.
By the way, I've never used fabric.js.
这篇关于Fabric.js中的多个画布(页面)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!