Moving ball
by jywglady
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Moving Ball</title>
<script src="https://unpkg.com/konva@3.4.1/konva.min.js"></script>
</head>
<body>
<div id="container"></div>
<button onclick="toLeft()">← To Left</button>
<button onclick="stopBall()">stop</button>
<button onclick="toRight()">To Right → </button>
</body>
</html>
CSS
#container {
width: 600px;
height: 200px;
border: solid blue 1px;
margin: 0 auto;
}
body {
text-align: center;
}
JavaScript
var width = 600;
var height = 200;
var stage = new Konva.Stage( {
container: 'container',
width: width,
height: height
});
var layer = new Konva.Layer();
var ball = new Konva.Circle({
x: width/2,
y: height/2,
radius:30,
fill:'blue'
});
layer.add(ball);
stage.add(layer);
var dir = 0;
var speed = 200; // pixels per second
var aniBall = new Konva.Animation(function(frame){
console.log("Running", dir);
if (dir != 0) {
ball.move({x: dir*speed*frame.timeDiff/1000, y:0});
if(ball.x() >= width) {
aniBall.stop()
dir = 0;
ball.x(width);
}
if(ball.x() <= 0) {
aniBall.stop()
dir = 0;
ball.x(0);
}
}
}, layer);
function toRight() {
console.log("Right")
dir = 1;
aniBall.start();
}
function toLeft() {
dir = -1;
aniBall.start();
}
function stopBall() {
dir = 0;
aniBall.stop();
}