Ok, so I have an animated diagram that animates multiple lines and shapes at the same time. Once the user plays the animation, I want he/she to be able to hit pause and the whole thing stop, then start again when the user hits the play button once more. I shouldn't need a loop to do this as it should do it with each mouse click. Here's a sample of the code.
var tween = new Kinetic.Tween({
node: lineTween,
points: [563.965, 258.163, 604.272, 258.163],
duration: 2
});
var tween3 = new Kinetic.Tween({
node: path3,
points: [582.81, 257.901, 582.81, 214.216],
duration: 2,
onFinish: function(){
tween3a.play();
}
});
document.getElementById('play').addEventListener('click', function(){
tween.play(
setTimeout(function(){
tween3.play();
}, 1000)
);
}, false);
document.getElementById('pause').addEventListener('click', function(){
tween.pause();
}, false);
Anyone have any suggestions?
You will have to store all tweens and turn them off/on:
Demo: http://jsfiddle.net/m1erickson/rF3Mm/
Code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Prototype</title>
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script src="http://d3lp1msu2r81bx.cloudfront.net/kjs/js/lib/kinetic-v4.7.2.min.js"></script>
<style>
body{padding:20px;}
#container{
border:solid 1px #ccc;
margin-top: 10px;
width:350px;
height:350px;
}
</style>
<script>
$(function(){
var stage = new Kinetic.Stage({
container: 'container',
width: 350,
height: 350
});
var layer = new Kinetic.Layer();
stage.add(layer);
$(stage.getContent()).on('click', function (event) {
var pos = stage.getMousePosition();
var mouseX = parseInt(pos.x);
var mouseY = parseInt(pos.y);
});
var tweens = [];
var circle1 = new Kinetic.Circle({
x: 30,
y: 100,
radius: 20,
fill: 'blue',
stroke: 'black',
strokeWidth: 4,
draggable: true
});
layer.add(circle1);
var circle2 = new Kinetic.Circle({
x: 30,
y: 30,
radius: 15,
fill: 'red',
stroke: 'black',
strokeWidth: 4,
draggable: true
});
layer.add(circle2);
layer.draw();
var tween1 = new Kinetic.Tween({
node: circle1,
duration: 15,
x: 250,
y: 250,
});
tweens.push(tween1);
var tween2 = new Kinetic.Tween({
node: circle2,
duration: 15,
x: 250,
y: 250,
});
tweens.push(tween2);
tween1.play();
tween2.play();
isPaused = false;
$("#toggle").click(function () {
if (isPaused) {
for (var i = 0; i < tweens.length; i++) {
tweens[i].play();
}
} else {
for (var i = 0; i < tweens.length; i++) {
tweens[i].pause();
}
}
isPaused = !isPaused
});
}); // end $(function(){});
</script>
</head>
<body>
<button id="toggle">Toggle:Pause/Resume</button>
<div id="container"></div>
</body>
</html>
Related
WARNING: turn the volume down before you run the snippet!
I want to be able to click on the stage to add a 'module' shape. But I have found that a click on the 'module' shape itself creates another, meaning that the stage.click listener is being fired when it should not be.
How can I have a stage.click listener that does not fire incorrectly when I click on a shape ?
var width = window.innerWidth;
var height = window.innerHeight;
var rectButtonClicked = false;
var stage = new Konva.Stage({
container: 'container',
width: width,
height: height
});
var layer = new Konva.Layer();
var group = new Konva.Group({
draggable: true
});
stage.on('contentClick', function() {
createModule();
});
function createModule() {
var mouseX = stage.getPointerPosition().x;
var mouseY = stage.getPointerPosition().y;
var rect = new Konva.Rect({ //module rect
x: mouseX,
y: mouseY,
width: 100,
height: 50,
cornerRadius: 5,
fill: '#BEDBDD',
stroke: '#807C7B',
strokeWidth: 2,
draggable: true
});
group.add(rect);
var buttonRect = new Konva.Rect({ //button
x: mouseX+80,
y: mouseY+20,
width: 10,
height: 10,
cornerRadius: 1,
fill: 'blue',
stroke: '#807C7B',
strokeWidth: 1,
});
group.add(buttonRect)
var text = new Konva.Text({ //text on module
x: mouseX + 20,
y: mouseY + 20,
//fontFamily: 'Calibri',
fontSize: 16,
text: 'OSC',
fill: 'black'
});
group.add(text);
var randomFreq = getRandomInt();
var osc = new Tone.Oscillator(randomFreq, "sawtooth");
layer.add(group);
stage.add(layer);
buttonRect.on('click', function() {
rectButtonClicked = !rectButtonClicked;
if(rectButtonClicked){
osc.toMaster().start();
this.setFill('red');
} else {
osc.stop();
this.setFill('blue');
}
});
}
function getRandomInt() {
min = Math.ceil(100);
max = Math.floor(1000);
return Math.floor(Math.random() * (max - min)) + min;
}
var width = window.innerWidth;
var height = window.innerHeight;
//var drag = false;
var rectButtonClicked = false;
var stage = new Konva.Stage({
container: 'container',
width: width,
height: height
});
var layer = new Konva.Layer();
var group = new Konva.Group({
draggable: true
});
stage.on('contentClick', function() {
createModule();
});
function createModule() {
var mouseX = stage.getPointerPosition().x;
var mouseY = stage.getPointerPosition().y;
var rect = new Konva.Rect({ //module rect
x: mouseX,
y: mouseY,
width: 100,
height: 50,
cornerRadius: 5,
fill: '#BEDBDD',
stroke: '#807C7B',
strokeWidth: 2,
draggable: true
});
group.add(rect);
var buttonRect = new Konva.Rect({ //button
x: mouseX+80,
y: mouseY+20,
width: 10,
height: 10,
cornerRadius: 1,
fill: 'blue',
stroke: '#807C7B',
strokeWidth: 1,
});
group.add(buttonRect)
var text = new Konva.Text({ //text on module
x: mouseX + 20,
y: mouseY + 20,
//fontFamily: 'Calibri',
fontSize: 16,
text: 'OSC',
fill: 'black'
});
group.add(text);
var randomFreq = getRandomInt();
var osc = new Tone.Oscillator(randomFreq, "sawtooth");
layer.add(group);
stage.add(layer);
buttonRect.on('click', function() {
rectButtonClicked = !rectButtonClicked;
if(rectButtonClicked){
osc.toMaster().start();
this.setFill('red');
} else {
osc.stop();
this.setFill('blue');
}
});
}
function getRandomInt() {
min = Math.ceil(100);
max = Math.floor(1000);
return Math.floor(Math.random() * (max - min)) + min;
}
<script src="https://tonejs.github.io/build/Tone.min.js"></script>
<script src="https://cdn.rawgit.com/konvajs/konva/1.7.6/konva.min.js"></script>
<div id="container"></div>
The stage.contentClick() listener is a special case to be used when you want the stage to listen to events on the stage content. However, the cancelBubble() function does not stop events bubbling from say a click on a shape to the stage.contentClick() listener.
To get the effect that you want, which is to give the impression that a click on the stage has happened, you need to add a rect that fills the stage and listen for events on that rect instead of the stage.
Below is a working example. The red background I added deliberately so you know there is something else above the stage. To remove this take out the fill color on the clickRect.
I also fixed up your buttons so that the contents are correctly grouped and drag together. You were almost correct but you needed the group to be created within in the createModule() function. You can see that I also made the group elements dragabble = false to complete the process.
I added a couple of console writes to show when the events fire.
[Also I got quite a shock when I switched on the tone for tone].
var width = window.innerWidth;
var height = window.innerHeight;
//var drag = false;
var rectButtonClicked = false;
var stage = new Konva.Stage({
container: 'container',
width: width,
height: height
});
var layer = new Konva.Layer();
stage.add(layer);
var clickRect = new Konva.Rect({
x:0,
y:0,
width: width,
height: height,
fill: 'red',
stroke: '#807C7B',
strokeWidth: 2,
listening: 'true'
})
layer.add(clickRect);
clickRect.on('click', function() {
console.log('Stage click');
createModule();
});
function createModule() {
var group = new Konva.Group({ // move group create into createModule
draggable: true // we will make the elements not draggable - we drag the group
});
var mouseX = stage.getPointerPosition().x;
var mouseY = stage.getPointerPosition().y;
var rect = new Konva.Rect({ //module rect
x: mouseX,
y: mouseY,
width: 100,
height: 50,
cornerRadius: 5,
fill: '#BEDBDD',
stroke: '#807C7B',
strokeWidth: 2,
draggable: false // make the element not draggable - we drag the group
});
group.add(rect);
rect.on('click', function(evt){
console.log('Clicked on button');
})
var buttonRect = new Konva.Rect({ //button
x: mouseX+80,
y: mouseY+20,
width: 10,
height: 10,
cornerRadius: 1,
fill: 'blue',
stroke: '#807C7B',
strokeWidth: 1,
listening: true,
draggable: false // make the element not draggable - we drag the group
});
group.add(buttonRect)
var text = new Konva.Text({ //text on module
x: mouseX + 20,
y: mouseY + 20,
//fontFamily: 'Calibri',
fontSize: 16,
text: 'OSC',
fill: 'black',
draggable: false // make the element not draggable - we drag the group
});
group.add(text);
var randomFreq = getRandomInt();
var osc = new Tone.Oscillator(randomFreq, "sawtooth");
layer.add(group);
stage.add(layer);
buttonRect.on('click', function(evt) {
rectButtonClicked = !rectButtonClicked;
if(rectButtonClicked){
osc.toMaster().start();
this.setFill('red');
} else {
osc.stop();
this.setFill('blue');
}
});
}
function getRandomInt() {
min = Math.ceil(100);
max = Math.floor(1000);
return Math.floor(Math.random() * (max - min)) + min;
}
stage.draw(); // draw so we can see click rect.
<script src="https://tonejs.github.io/build/Tone.min.js"></script>
<script src="https://cdn.rawgit.com/konvajs/konva/1.7.6/konva.min.js"></script>
<div id="container" style="background-color: gold;"></div>
Disclaimer: it may be considered this post is a duplicate of this post but I have demonstrated my need specifically.
I have a case in my KonvaJS application where I need to propagate a click event from the Rectangle shape (that is a child of the Upper Layer) to several images that are added to the Lower Layer.
Please note that I have in the Lower layer more than 50 objects between images and shapes, so how can I now what is the target object in the Lower Layer.
Kindly here is an example to demonstrate my need:
var width = window.innerWidth;
var height = window.innerHeight;
var stage = new Konva.Stage({
container: 'container',
width: width,
height: height
});
var lowerLayer = new Konva.Layer();
var upperLayer = new Konva.Layer();
//lion
var lionImage = new Image();
lionImage.onload = function() {
var lion = new Konva.Image({
x: 50,
y: 50,
image: lionImage,
width: 106,
height: 118
});
// add the shape to the layer
lowerLayer.add(lion);
stage.draw();
lion.on("click", function() {
alert("you clicked the lion");
});
};
lionImage.src = 'http://konvajs.github.io/assets/lion.png';
//monkey
var monkeyImage = new Image();
monkeyImage.onload = function() {
var monkey = new Konva.Image({
x: 200,
y: 50,
image: monkeyImage,
width: 106,
height: 118
});
// add the shape to the layer
lowerLayer.add(monkey);
stage.draw();
monkey.on("click", function() {
alert("you clicked the monkey");
});
};
monkeyImage.src = 'http://konvajs.github.io/assets/monkey.png';
var upperTransparentBox = new Konva.Rect({
x: 0,
y: 0,
height: stage.height(),
width: stage.width(),
fill: 'transparent',
draggable: false,
name: 'upperTransparentBox'
});
upperTransparentBox.on("click", function() {
alert("you clicked the upper Transparent Box");
});
upperLayer.add(upperTransparentBox);
// add the layer to the stage
stage.add(lowerLayer);
stage.add(upperLayer);
<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.rawgit.com/konvajs/konva/1.0.2/konva.min.js"></script>
<meta charset="utf-8">
<title>Konva Image Demo</title>
<style>
body {
margin: 0;
padding: 0;
overflow: hidden;
background-color: #F0F0F0;
}
</style>
</head>
<body>
<div id="container"></div>
</body>
</html>
Technically it is possible to manually trigger click event on any node.
But I think it is an antipattern. You can just find an intersection with 'getIntersection()' function and do what you need with a node.
var width = window.innerWidth;
var height = window.innerHeight;
var stage = new Konva.Stage({
container: 'container',
width: width,
height: height
});
var lowerLayer = new Konva.Layer();
var upperLayer = new Konva.Layer();
//lion
var lionImage = new Image();
lionImage.onload = function() {
var lion = new Konva.Image({
x: 50,
y: 50,
name: 'lion',
image: lionImage,
width: 106,
height: 118
});
// add the shape to the layer
lowerLayer.add(lion);
stage.draw();
lion.on("click", function() {
alert("you clicked the lion");
});
};
lionImage.src = 'http://konvajs.github.io/assets/lion.png';
//monkey
var monkeyImage = new Image();
monkeyImage.onload = function() {
var monkey = new Konva.Image({
x: 200,
y: 50,
name: 'monkey',
image: monkeyImage,
width: 106,
height: 118
});
// add the shape to the layer
lowerLayer.add(monkey);
stage.draw();
monkey.on("click", function() {
alert("you clicked the monkey");
});
};
monkeyImage.src = 'http://konvajs.github.io/assets/monkey.png';
var upperTransparentBox = new Konva.Rect({
x: 0,
y: 0,
height: stage.height(),
width: stage.width(),
fill: 'transparent',
draggable: false,
name: 'upperTransparentBox'
});
upperTransparentBox.on("click", function() {
var target = lowerLayer.getIntersection(stage.getPointerPosition());
if (target) {
alert('clicked on ' + target.name());
}
});
upperLayer.add(upperTransparentBox);
// add the layer to the stage
stage.add(lowerLayer);
stage.add(upperLayer);
<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.rawgit.com/konvajs/konva/1.0.2/konva.min.js"></script>
<meta charset="utf-8">
<title>Konva Image Demo</title>
<style>
body {
margin: 0;
padding: 0;
overflow: hidden;
background-color: #F0F0F0;
}
</style>
</head>
<body>
<div id="container"></div>
</body>
</html>
I am trying to recreate the game http://www.sinuousgame.com/ and studying html5 canvas and kineticJS.
This is my fiddle:
http://jsfiddle.net/2WRwY/7/
My problem:
The tail part of the player in the fiddle doesn't seem to retract back.
The red ball objects should appear over the player objects.
(Try running the fiddle with layer.removeChildren(); and without it.)
Right now,I have commented "layer.removeChildren();" on the fiddle.. (basically which causes the problem for me)
Here's my html:
<!DOCTYPE html>
<html>
<head>
<title>Collision Detection-player</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" href="../css/style.css"/>
</head>
<body>
<div id="container" style="width: auto; height: auto; background:#000; margin:auto; float:left;"></div>
<script src="../js/jquery.min.js"></script>
<script src="../js/kinetic-v5.0.0.min.js"></script>
<script src="../js/main_kinetic_combined.js"></script>
</body>
</html>
Here's my javascript:
//The working player code
var LimitedArray = function(upperLimit) {
var storage = [];
// default limit on length if none/invalid supplied;
upperLimit = +upperLimit > 0 ? upperLimit : 100;
this.push = function(item) {
storage.push(item);
if (storage.length > upperLimit) {
storage.shift();
}
return storage.length;
};
this.get = function(flag) {
return storage[flag];
};
this.iterateItems = function(iterator) {
var flag, l = storage.length;
if (typeof iterator !== 'function') {
return;
}
for (flag = 0; flag < l; flag++) {
iterator(storage[flag]);
}
};
};
var tail = new LimitedArray(50);
var flag = 0, jincr = 0;
var stage = new Kinetic.Stage({
container: 'container',
width: window.innerWidth,
height: window.innerHeight,
listening: true
});
var layer = new Kinetic.Layer({
listening: true
});
stage.add(layer);
var player = new Kinetic.Circle({
x: 20,
y: 20,
radius: 6,
fill: 'cyan',
stroke: 'black',
draggable: true
});
layer.add(player);
// move the circle with the mouse
stage.getContent().addEventListener('mousemove', function() {
<!--layer.removeChildren(); -->
layer.add(player);
player.setPosition(stage.getPointerPosition());
var obj = {
x: stage.getPointerPosition().x,
y: stage.getPointerPosition().y
};
tail.push(obj);
var arr = [];
tail.iterateItems(function(p) {
arr.push(p.x, p.y);
});
var line = new Kinetic.Line({
points: arr,
stroke: 'white',
strokeWidth: 2,
lineCap: 'round',
lineJoin: 'round'
});
layer.add(line);
// layer.draw();
});
var x = 0;
var y = 0;
var noOfEnemies = 150;
var enemyArmada = new Array();
createEnemy();
function createEnemy() {
for (var i = 0; i < noOfEnemies; i++) {
var enemy = new Kinetic.Circle({
x: Math.random() * window.innerWidth,
y: Math.random() * window.innerHeight,
radius: 4.5 + 1.5 * Math.random(),
fill: 'red',
stroke: 'black',
});
enemy.speedX = enemy.speedY = (0.3 + Math.random() * 50);
enemyArmada.push(enemy);
layer.add(enemy);
}
}
var anim = new Kinetic.Animation(function(frame) {
for (var i = 0; i < noOfEnemies; i++) {
var e = enemyArmada[i];
e.position({
x: e.position().x - e.speedX * frame.timeDiff / 500,
y: e.position().y + e.speedY * frame.timeDiff / 500
});
if (e.position().y < 0 || e.position().x < 0) {
e.position({
x: (Math.random() * (window.innerWidth + 600)),
y: -(Math.random() * window.innerHeight)
});
}
}
}, layer);
anim.start();
Any suggestions?
The problem is that after you've added the enemies, you're adding the player and the line to the layer again, so they'll be on top. Also, on each mouse move, you're creating the line over and over again.
So, instead, you should just update the line points (and you don't need the layer.removeChildren(); line at all), like this:
var line = new Kinetic.Line({
points: [],
stroke: 'white',
strokeWidth: 2,
lineCap: 'round',
lineJoin: 'round'
});
layer.add(line);
layer.add(player);
// move the circle with the mouse
stage.getContent().addEventListener('mousemove', function() {
player.position(stage.getPointerPosition());
var obj = {
x: stage.getPointerPosition().x,
y: stage.getPointerPosition().y
};
tail.push(obj);
var arr = [];
tail.iterateItems(function(p) {
arr.push(p.x, p.y);
});
line.points(arr);
});
See fiddle: http://jsfiddle.net/Kunstmord/p9fnq/2/
This way, you're only creating the line once. This also seems to fix the non-disappearing trail.
Also, please note:
1) use position instead of setPosition and getPosition (see KineticJS 5.0 docs)
2) adding <!-- --> does not comment out a line in Javascript (layer.removeChildren(); line).
i have following code to drag a smaller rect in a bigger rect.
it is almost working, but its possible to move the orange rect out of the white one.
Is there any solution for this behavior?? that the bigger rect is the dragborder for the small rect??
And another question... would it be possible to do it for a rect in any polygon as border?
<!DOCTYPE HTML>
<html>
<head>
<style>
body {margin: 0px; padding: 20px;}
canvas {border: 1px solid #777;}
</style>
</head>
<body>
<div id="container"></div>
<script src="http://d3lp1msu2r81bx.cloudfront.net/kjs/js/lib/kinetic-v4.3.2.js"></script>
<script>
var stage = new Kinetic.Stage({
container: 'container',
width: 300,
height: 300
});
var layer = new Kinetic.Layer();
// White box
var white = new Kinetic.Rect({
x: 100,
y: 50,
width: 150,
height: 100,
fill: 'white',
stroke: 'black',
strokeWidth: 2
});
// orange box
var orange = new Kinetic.Rect({
x: 150,
y: 100,
width: 50,
height: 30,
fill: 'orange',
stroke: 'black',
strokeWidth: 2,
draggable: true,
// this causes orange box to be stopped if try to leave white box
dragBoundFunc: function(pos){
if(theyAreColliding(orange,white)){
// orange box is touching white box
// let it move ahead
return ({ x:pos.x, y:pos.y });
} else{
// orange box is not touching white box
// don't let orange box move outside
if (white.getY() > orange.getY()){
return({x: pos.x, y: white.getY()+1});
}
else if (white.getY() + white.getHeight() - orange.getHeight() < orange.getY()){
return({x: pos.x, y: white.getY() + white.getHeight() - orange.getHeight() -1});
}
else if (white.getX() > orange.getX()){
return({x: white.getX() +1, y: pos.y})
}
else if (white.getX() + white.getWidth() - orange.getWidth() < orange.getX()){
return({x: white.getX() +white.getWidth() - orange.getWidth() -1, y: pos.y})
}
}
}
});
function theyAreColliding(rect1, rect2) {
return !(rect2.getX() > rect1.getX() ||
rect2.getX() + rect2.getWidth() - rect1.getWidth() < rect1.getX() ||
rect2.getY() > rect1.getY() ||
rect2.getY() + rect2.getHeight() - rect1.getHeight() < rect1.getY());
}
layer.add(white);
layer.add(orange);
stage.add(layer);
</script>
</body>
</html>
and also the jsfiddle link: http://jsfiddle.net/dNfjM/
This is an improved way of setting your dragBoundFunc
The secret with dragBoundFunc is to allow it to execute fast. Remember that it is being executed with every mousemove.
So, pre-calculate all the minimum and maximum boundaries before and outside dragBoundFunc, like this:
// pre-calc some bounds so dragBoundFunc has less calc's to do
var height=orangeRect.getHeight();
var minX=white.getX();
var maxX=white.getX()+white.getWidth()-orangeRect.getWidth();
var minY=white.getY();
var maxY=white.getY()+white.getHeight()-orangeRect.getHeight();
That way your dragBoundFunc can just test the current position against these pre-calc’ed bounds like this:
dragBoundFunc: function(pos) {
var X=pos.x;
var Y=pos.y;
if(X<minX){X=minX;}
if(X>maxX){X=maxX;}
if(Y<minY){Y=minY;}
if(Y>maxY){Y=maxY;}
return({x:X, y:Y});
}
Here’s code and a Fiddle: http://jsfiddle.net/m1erickson/n5xMs/
<!DOCTYPE HTML>
<html>
<head>
<style>
body {
margin: 0px;
padding: 10px;
}
canvas{border:1px solid red;}
</style>
</head>
<body>
<div id="container"></div>
<script src="http://d3lp1msu2r81bx.cloudfront.net/kjs/js/lib/kinetic-v4.4.1.min.js"></script>
<script>
var stage = new Kinetic.Stage({
container: 'container',
width: 400,
height: 400
});
var layer = new Kinetic.Layer();
var white = new Kinetic.Rect({
x: 20,
y: 20,
width: 300,
height: 300,
fill: 'white',
stroke: 'black',
strokeWidth: 2
});
var orangeGroup = new Kinetic.Group({
x: stage.getWidth() / 2,
y: 70,
draggable: true,
dragBoundFunc: function(pos) {
var X=pos.x;
var Y=pos.y;
if(X<minX){X=minX;}
if(X>maxX){X=maxX;}
if(Y<minY){Y=minY;}
if(Y>maxY){Y=maxY;}
return({x:X, y:Y});
}
});
var orangeText = new Kinetic.Text({
fontSize: 26,
fontFamily: 'Calibri',
text: 'boxed in',
fill: 'black',
padding: 10
});
var orangeRect = new Kinetic.Rect({
width: orangeText.getWidth(),
height: orangeText.getHeight(),
fill: 'orange',
stroke: 'blue',
strokeWidth: 4
});
orangeGroup.add(orangeRect).add(orangeText);
layer.add(white);
layer.add(orangeGroup);
stage.add(layer);
// pre-calc some bounds so dragBoundFunc has less calc's to do
var height=orangeRect.getHeight();
var minX=white.getX();
var maxX=white.getX()+white.getWidth()-orangeRect.getWidth();
var minY=white.getY();
var maxY=white.getY()+white.getHeight()-orangeRect.getHeight();
</script>
</body>
</html>
I have a draggable circle shape that the user drags to another circle shape [static, non-draggable]. When the draggable circle overlaps the static circle, I need to display a "Success" text. How can I do so ?
When the user drags the circle, you can handle the “dragmove” events.
In "dragmove": test whether the circles are colliding. If so, then declare success!
Circle1.on("dragmove",function(){
if(theyAreColliding(Circle1,Circle2)){
// Success!
}
});
The test for collision looks like this:
function theyAreColliding(c1,c2){
var dx=c1.getX()-c2.getX();
var dy=c1.getY()-c2.getY();
var radiiSum=c1.getRadius()+c2.getRadius();
console.log(dx+"/"+dy+": "+radiiSum);
return((dx*dx+dy*dy)<radiiSum*radiiSum);
}
Here is code and a Fiddle: http://jsfiddle.net/m1erickson/3dQpL/
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Prototype</title>
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script src="http://www.html5canvastutorials.com/libraries/kinetic-v4.3.3-beta.js"></script>
<style>
canvas{
border:solid 1px #ccc;
}
</style>
<script>
$(function(){
var layer = new Kinetic.Layer();
var stage = new Kinetic.Stage({
container: "container",
width: 400,
height: 400
});
stage.add(layer);
// mouse events don't fire on the empty part of the stage
// so fill the stage with a rect to get events on entire stage
// now stage.on("mouse... will work
var background = new Kinetic.Rect({
x: 0,
y: 0,
width: 400, //stage.getWidth(),
height: 400, //stage.getHeight(),
fill: "#eee"
});
layer.add(background);
var Radius1=50;
var Circle1=new Kinetic.Circle({
x: 225,
y: 125,
radius: Radius1,
fill: 'green',
stroke: 'orange',
strokeWidth: 2,
draggable:true
});
layer.add(Circle1);
var Radius2=50;
var Circle2=new Kinetic.Circle({
x: 75,
y: 175,
radius: Radius2,
fill: 'blue',
stroke: 'black',
strokeWidth: 2
});
layer.add(Circle2);
var message = new Kinetic.Text({
x: 10,
y: 15,
text: "",
fontSize: 30,
fontFamily: 'Calibri',
fill: 'green'
});
layer.add(message);
var instructions = new Kinetic.Text({
x: 10,
y: 285,
text: "Drag green on top of blue",
fontSize: 18,
fontFamily: 'Calibri',
fill: 'green'
});
layer.add(instructions);
layer.draw();
Circle1.on("dragmove",function(){
if(theyAreColliding(Circle1,Circle2)){
message.setText("Collision Detected!");
Circle1.setFill("red");
layer.draw();
}else{
}
});
function theyAreColliding(c1,c2){
var dx=c1.getX()-c2.getX();
var dy=c1.getY()-c2.getY();
var radiiSum=c1.getRadius()+c2.getRadius();
console.log(dx+"/"+dy+": "+radiiSum);
return((dx*dx+dy*dy)<radiiSum*radiiSum);
}
}); // end $(function(){});
</script>
</head>
<body>
<div id="container"></div>
</body>
</html>