Skip to content

Script Examples

Draggable Locator

Download ezUI File

In this example, we created a draggable Icon that represents a Locator. by dragging the Icon, the X and Y Position values of the Locator are automatically updated. We also utilised the Joystick component to control our Locator.

To do this, we determine if the user has clicked the Draggable Icon and when the cursor is dragged, then we get the current position of the icon and clamp it, then we update the Vertex inputs and Slider to reflect the position of the Icon. You can also use the Slider and Vector inputs to update the position of the Icon, as well as it's orientation and Scale.

Locator

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
let drag = false;
const realSize = 200;
function onPointerDown(e) {
  drag = true;
  area.setPointerCapture(e.pointerId);
}


function onPointerUp(e) {
  drag = false;
  area.releasePointerCapture(e.pointerId);
}

area.onPointerDown = locator.onPointerDown = onPointerDown;
area.onPointerUp = locator.onPointerUp = onPointerUp;
area.onMouseMove = (e) => {
  if (!drag)
    return;

  updatePosition('x', e.relativeXNormalized * realSize);
  updatePosition('y', e.relativeYNormalized * realSize);
}

joystick1.onChange = (e) => {
  console.log(e.sender.name, e);
  if(e.delta?.x){
    updatePosition('x', vtxPosition.value.x + e.delta.x);
  }
  if(e.delta?.y){
    updatePosition('y', vtxPosition.value.y - e.delta.y);
  }
}

xSlider.onChange = (e) => updatePosition('x', xSlider.value * realSize);
ySlider.onChange = (e) => updatePosition('y', ySlider.value * realSize);
vtxRotation.onChange = (e) => locator.style.transform = `scale(${vtxScale.value.x}) rotate(${vtxRotation.value.x}deg)`;
vtxScale.onChange = (e) => locator.style.transform = `scale(${vtxScale.value.x}) rotate(${vtxRotation.value.x}deg)`;

function updatePosition(field, value) {
  let val = Math.max(0, Math.min(value, realSize));
  let v = vtxPosition.value;
  v[field] = value;

  vtxPosition.value = v;


  findElement(`${field}Slider`).value = val / realSize;

  locator.left = area.left + (Math.max(0, Math.min(vtxPosition.value.x, realSize)) / realSize) * area.width - locator.width / 2;
  locator.top = area.top + (Math.max(0, Math.min(vtxPosition.value.y, realSize)) / realSize) * area.height - locator.height / 2;
  locator.style.transform = `scale(${vtxScale.value.x}) rotate(${vtxRotation.value.x}deg)`;

}

// Initial Read
function readData() {
  updatePosition('x', vtxPosition.value.x);
  updatePosition('y', vtxPosition.value.y);
}

readData();