gpt4 book ai didi

javascript - 如何为 fabricjs 中的所有方法使用和访问多个 Canvas 的实例?

转载 作者:行者123 更新时间:2023-11-30 09:21:16 26 4
gpt4 key购买 nike

我为这个问题搜索了整整一个月,但我真的很难解决这个问题。以下是这个问题的类似答案,但没有一个适用于我的情况:

Multiple canvases (pages) in Fabric.js

How to manage memory in case of multiple fabric js canvas?

当我开始向 Canvas 添加文本和形状时出现错误:Uncaught TypeError: Cannot read property 'add' of undefined

错误从这里开始:

// add text on click
$('#add_text').on("click",function(event){
var Text = new fabric.Textbox('Sample');
canvasInstances[0].add(Text).renderAll();
});
// add circle on click
$('#add_circle').on("click",function(event){
var Circle = new fabric.Circle();
canvasInstances[0].add(Circle).renderAll();
});

Here is my jsfiddle

请帮忙!!!

最佳答案

在创建 Canvas 元素后创建织物 Canvas 实例,然后推送到您的 canvasInstances 数组。

演示

// store multiple instances in  the array
var canvasInstances = [];
// add canvas on click
$('.add_canvas').on("click", function(event) {
var content = document.getElementById("content");
var newcanvas = document.createElement("canvas");
content.appendChild(newcanvas);
var fabricCanvasObj = new fabric.Canvas(newcanvas);
canvasInstances.push(fabricCanvasObj);
});
// add text on click
$('#add_text').on("click", function(event) {
canvasInstances.forEach(function(canvas) {
var Text = new fabric.Textbox('Sample');
canvas.add(Text).renderAll();
})
});
// add circle on click
$('#add_circle').on("click", function(event) {
canvasInstances.forEach(function(canvas) {
var Circle = new fabric.Circle({
radius: 50,
left: 10,
top: 10
});
canvas.add(Circle).renderAll();
})
});
// error starts when adding text and circle in console log.
// what i wanted is to use all methods and access all
// instances in fabric to make all canvas editable
canvas{
border: 1px solid green;
margin: 5px;
z-index: 1;
}
.canvas-container{
margin: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.3.3/fabric.min.js"></script>
<button class='add_canvas'>Add Canvas</button>
<button id ='add_text'>Add Text</button>
<button id ='add_circle'>Add Circle</button>
<div id="content"></div>

关于javascript - 如何为 fabricjs 中的所有方法使用和访问多个 Canvas 的实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51477707/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com