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);
testStage.add(testLayer);
document.body.appendChild(con);
animateButton.appendChild(t);
animateButton.addEventListener('click', e => {
let i = 0;
let _ctx = testLayer.getContext()._context;
let draw = () => {
setTimeout(() => {
if (routes.length) {
_ctx.clearRect(0, 0, 300, 300);
_ctx.beginPath();
_ctx.moveTo(routes[0].x, (routes[0].y * -1));
for (let p = 1, plen = i; p < plen; p++) {
_ctx.lineTo(routes[p].x, (routes[p].y * -1));
}
_ctx.strokeStyle = '#000';
_ctx.lineWidth = 1.5;
_ctx.stroke();
(i === routes.length - 1) ? i = 0: i++;
}
requestAnimationFrame(draw);
}, 1000 / 59.940);
}
draw();
});
document.body.appendChild(animateButton);