JSFiddle - React, Tailwind, and code Playground

by ksumarine

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/konva/1.7.6/konva.js"></script>

CSS

canvas {
  border: 1px solid #000 !important;
}

JavaScript

let con = document.createElement('div');
let animateButton = document.createElement('button');
let t = document.createTextNode("Animate");
let routes = [{
  x: 0,
  y: 0
}, {
  x: 1,
  y: -2
}, {
  x: 2,
  y: -4
}, {
  x: 3,
  y: -6
}, {
  x: 4,
  y: -8
}, {
  x: 5,
  y: -10
}, {
  x: 6,
  y: -12
}, {
  x: 7,
  y: -14
}, {
  x: 8,
  y: -16
}, {
  x: 9,
  y: -18
}, {
  x: 10,
  y: -20
}, {
  x: 11,
  y: -22
}, {
  x: 12,
  y: -24
}, {
  x: 13,
  y: -26
}, {
  x: 14,
  y: -28
}, {
  x: 15,
  y: -30
}];
let testStage = new Konva.Stage({
  container: con,
  x: 0,
  y: 0,
  width: 300,
  height: 300,
  offsetX: ((300 / 2) * -1),
  offsetY: (300 * -1)
});
let testLayer = new Konva.Layer();
let testShape = new Konva.Shape({
  sceneFunc: function(context) {
    context.beginPath();
    for (var i = 0; i < routes.length - 1; i++) {
      context.moveTo(routes[i].x, routes[i].y);
      context.lineTo(routes[i + 1].x, routes[i + 1].y);
    }
    context.strokeStyle = '#000';
    context.lineWidth = 1.5;
    context.stroke();
  }
});
testLayer.add(testShape);


let animateLayer = new Konva.Layer();
let ball = new Konva.Circle({
  x: routes[0].x,
  y: routes[0].y,
  fill: 'red',
  radius: 5
});
animateLayer.add(ball);

testStage.add(testLayer);
testStage.add(animateLayer);

let i = 0;
let isAnimating = false;
let ani = new Konva.Animation(frame => {
  ball.setX(routes[i].x);
  ball.setY(routes[i].y);

  (i === routes.length - 1) ? i = 0: i++;
}, animateLayer);

document.body.appendChild(con);
animateButton.appendChild(t);
animateButton.addEventListener('click', e => {
	isAnimating = !isAnimating;
  if (isAnimating) {
  	ani.start();	
  } else {
  	ani.stop();
  }
});
document.body.appendChild(animateButton);