Skip to content Skip to sidebar Skip to footer

Add An Html Class To A Dom Element Controlled By Two.js

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 'b

Solution 1:

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.Scenevar my_scene = two.renderer.domElement;

// Two.Groupvar 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 shapevar 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();

Post a Comment for "Add An Html Class To A Dom Element Controlled By Two.js"