Vector.js

Vector is an open source javascript library for creating interactive graphics. View the repository, browse the API, run the tests, or meet the team.

Control With Position

This tutorial demonstrates how to add a text label to a control point and then make the label follow and display the position of the point using reactive programming syntax. We assume you have gone through the getting started tutorial to get to the starting point.

Starting point

The starting point is an interactive with a control point that can be dragged around.

1import Interactive from '/interactive.js';
2
3// Initialize the interactive
4let interactive = new Interactive("step-0");
5interactive.border = true;
6
7// Create a control point at the location (100, 100)
8let control = interactive.control( 100, 100);

Adding a Text Label

Next we are going to create a text element at a random position within the interactive.

10// Create a text element at the location (150,150);
11let text = interactive.text(150, 150, "myText");

Declaring a Dependency

Then we are going to declare a dependency so that when the state of the control point changes, our text element’s update function will be called.

14text.addDependency(control);
15text.update = function() {
16  // update the text element when the control changes
17}

Update Function

Let’s make it so the text element’s position follows the position of the control point and the contents of the text displays the position of the point.

13// Update the text when the control changes
14text.addDependency(control);
15text.update = function() {
16
17  // update the position of the text element
18  this.x = control.x + 15;
19  this.y = control.y - 15;
20
21  // update the contents to be the position of the point
22  this.contents = `(${control.x},${control.y})`;
23};
24text.update();

Onward

To learn more follow other tutorials, browse and fork examples, or read the documentation.