two.js 实体本身不是 DOM 元素,但每个 Scene、Group 或 Polygon 至少包含一个对实体更改时绘制的 DOM 元素的引用。要引用各种 DOM 元素,请使用以下语法:
// Initialize two.js and attach to a dom element referenced by `canvas`
var two = new Two(params).appendTo(canvas);
// Two.Scene
var my_scene = two.renderer.domElement;
// Two.Group
var my_group = document.getElementById(two.scene.id);
// Two.Polygon — requires knowing the ID by means of your custom app logic.
var my_poly = document.getElementById(my_poly_html_id);
my_poly.classList.add('my-class');
这是一个屏幕截图,显示了实际应用程序中的所有三个命令以及每个命令的结果,另外还有一个命令将一个类添加到目标形状。最后一个命令的语法不同,但我省略了var
语句,以便控制台显示结果而不是输出undefined
.
如果您想为单个形状创建自定义 HTML ID,.id
请在初始渲染形状之前使用 setter。由于大部分代码只是设置,因此我在我自己的一个项目中提供了一个实际示例。在该代码段中,一个变量在第一次调用绘制形状之前保存了一个新的so 调用shape
实例,这会导致一个具有自定义 HTML ID 的 DOM 元素。这是一个不完整的设置代码块,显示了如何设置 ID:Two.Polygon
shape.id = 'something-unique'
two.update()
// Create new shape
var shape = two.makeRectangle(START_X, START_Y, START_WIDTH, START_HEIGHT);
// Set custom ID
shape.id = 'shape-' + Math.random(10000000);
// Draw shape for first time.
two.update();