javascript 使用fabric js时获取canvas对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13195481/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 18:02:26  来源:igfitidea点击:

Get the canvas object while using fabric js

javascriptjqueryhtml5-canvasfabricjs

提问by viji

I'm using Fabric.js and I've created a fabric canvas object at one place.

我正在使用 Fabric.js,并且在一个地方创建了一个 Fabric 画布对象。

var x = new fabric.Canvas("mycanvas");

Now at another place, I want to access this object where 'x' won't be available. So how can I get the same fabric canvas object.

现在在另一个地方,我想访问“x”不可用的这个对象。那么我怎样才能获得相同的织物画布对象。

I don't wanna change the scope of x or pass x as arg.

我不想更改 x 的范围或将 x 作为 arg 传递。

Also, how to get the toDataURL from the fabric canvas object?

另外,如何从结构画布对象中获取 toDataURL?

回答by Alnitak

Assuming that mycanvasis the ID of a Canvas element, you could store the reference to the fabric object on the Canvas element itself:

假设这mycanvas是 Canvas 元素的 ID,您可以在 Canvas 元素本身上存储对结构对象的引用:

var x = new fabric.Canvas("mycanvas");
document.getElementById("mycanvas").fabric = x;

You can then retrieve that object any time you want with:

然后,您可以随时使用以下命令检索该对象:

var y = document.getElementById("mycanvas").fabric;
var url = y.toDataURL("png", 1);