Add an HTML class to a DOM element controlled by t

2019-08-12 01:20发布

I'm trying to add a class and ID to specific Two.js objects in this project: http://itpblog.evejweinberg.com/Homework/Open/ (click a few times to play) If I console.log the word 'background' I see that these are two.js objects but I can't seem to use css or jquery to add a class/ID to them.

Any help is appreciated!

I even tried adding it to the whole project but that did not work:

$(document.body).addClass("dropshadow");

1条回答
祖国的老花朵
2楼-- · 2019-08-12 02:05

two.js entities are not DOM elements themselves, but each Scene, Group, or Polygon contains at least one reference to the DOM element that gets drawn when the entity is changed. To reference various DOM elements use the following syntaxes:

// 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');

Here's a screenshot showing all three commands in an actual app along with the outcome of each, with one additional command add a class to the shape that was targeted. The syntax of the last command differs but I omitted the var statements so that the console would display the result instead of outputting undefined.

screenshot of a two.js scene and console output of the previously listen commands

If you'd like to create custom HTML IDs for individual shapes, use the .id setter before the initial render of your shape. Since most of this code is just setup, I offer a practical example on one of my own projects. In that snippet, a shape variable holds a new instance of Two.Polygon so calling shape.id = 'something-unique' before calling two.update() to draw the shape for the first time results in a DOM element with a custom HTML ID. Here is an incomplete block of setup code showing how to set the ID:

// 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();
查看更多
登录 后发表回答