In kineticjs I am creating dynamic rectangles that are draggable. However when I create a new rectangle, the rectangle behind it automatically drags. I dont want this to happen.
You can see the behaviour in demo at http://jsfiddle.net/sandeepy02/8kGVD/12/
Step 1: Choose "create rectangle" and create rectangles.
Step 2: Choose "Move rectangle" and move the rectangles.
Step 3: Choose "create rectangle" and create rectangles. This causes the rectangles previously created to also move. This is unwanted.
<html>
<head>
<script>
function valButton(radios) {
var btn = document.getElementsByName(radios);
var cnt = -1;
for (var i = btn.length - 1; i > -1; i--) {
if (btn[i].checked) {
cnt = i;
i = -1;
}
}
if (cnt > -1) return btn[cnt].value;
else return null;
}
window.onload = function() {
layer = new Kinetic.Layer();
stage = new Kinetic.Stage({
container: "container",
width: 320,
height: 320
});
background = new Kinetic.Rect({
x: 0,
y: 0,
width: stage.getWidth(),
height: stage.getHeight(),
fill: "white"
});
layer.add(background);
stage.add(layer);
moving = false;
stage.on("mousedown touchstart", function() {
var btnName = valButton("group2");
if (btnName == "1") {
if (moving) {
moving = false;
layer.draw();
} else {
var mousePos = stage.getMousePosition();
rect = new Kinetic.Rect({
x: 22,
y: 7,
width: 0,
height: 0,
fill: 'red',
stroke: 'black',
strokeWidth: 4,
draggable: true
});
layer.add(rect);
//start point and end point are the same
rect.setX(mousePos.x);
rect.setY(mousePos.y);
rect.setWidth(0);
rect.setHeight(0);
moving = true;
layer.drawScene();
}
}
document.all.text.innerText = btnName +" "+moving;
}); //end of mousedown
stage.on("mousemove touchmove", function() {
var btnName = valButton("group2");
if (btnName == "1") {
if (moving) {
var mousePos = stage.getMousePosition();
var x = mousePos.x;
var y = mousePos.y;
rect.setWidth(mousePos.x - rect.getX());
rect.setHeight(mousePos.y - rect.getY());
moving = true;
layer.drawScene();
}
}
else if (btnName == "3") {
layer.draw();
}
document.all.text.innerText = btnName +" "+moving;
}); //end of mousemove
stage.on("mouseup touchend", function() {
var btnName = valButton("group2");
if (btnName == "1") {
moving = false;
}
document.all.text.innerText = btnName +" "+moving;
}); //end of mouseup
};
</script>
</head>
<body>
<h2>Toggle buttons</h2>
<div class="toggle-btn-grp">
<label onclick="" class="toggle-btn"><input type="radio" value="1" name="group2"/> Create Rectangle</label>
<label onclick="" class="toggle-btn"><input type="radio" value="3" name="group2"/>Move Rectangle</label>
</div>
<div id="container" ></div>
<div id="text" >abc</div>
</body>
</html>
Here is your updated function to fix the problem -
stage.on("mousedown touchstart", function() {
var btnName = valButton("group2");
if (btnName == "Create") {
if (moving) {
moving = false;
layer.draw();
} else {
var mousePos = stage.getMousePosition();
rect = new Kinetic.Rect({
x: 0,
y: 0,
width: 0,
height: 0,
fill: 'red',
stroke: 'black',
strokeWidth: 4,
draggable: true
});
layer.add(rect);
//start point and end point are the same
rect.setX(mousePos.x);
rect.setY(mousePos.y);
rect.setWidth(0);
rect.setHeight(0);
moving = true;
rect.on("mousemove touchmove", function() {
var btnName = valButton("group2");
if (btnName == "Create") {
this.setDraggable(false);
}
else if (btnName == "Move") {
this.setDraggable(true);
}
document.all.text.innerText = btnName +" rect move MovingFlag: "+moving;
}); //end of rect mousemove
layer.drawScene();
}
}
document.all.text.innerText = btnName +" MovingFlag: "+moving;
}); //end of mousedown
Related
I have a stage with a lot of shapes, and I would like to move one shape using the keyboard UP, Down, Left, and Right when it is clicked. The implementation was working for one element, but when I have more than one, all elements are moved when keydown is pressed.I found an example on the Konva site, bat it works for one element. I try to remove the event when the mouse was moving waiting for the next click in some shape element, but it doesn't work too. How I can do it?
My code
<div id="container"></div>
<script>
var stage = new Konva.Stage({
container: 'container',
width: window.innerWidth,
height: window.innerHeight,
});
var layer = new Konva.Layer();
stage.add(layer);
var circle = new Konva.Circle({
x: stage.width() / 2,
y: stage.height() / 2 + 10,
radius: 70,
fill: 'red',
stroke: 'black',
strokeWidth: 4,
});
layer.add(circle);
var rect = new Konva.Rect({
x: 300,
y: 10,
width: 70,
height: 70,
stroke: 'black',
fill: 'blue',
strokeWidth: 2,
cornerRadius: 2,
id: 'cRectSquare',
visible: true,
draggable: true,
});
layer.add(rect);
//add event keydown
stage.on('click', function (e) {
if (e.target === stage) {
return;
}
let currentShape = e.target;
AddKeyboardEventToShape(currentShape);
});
stage.on('mousemove', function (e) {
var container = stage.container();
container.tabIndex = 0;
container.focus(false);
container.off('keydown');
container.removeEventListener('keydown', function (e) {
e.preventDefault();
});
return;
});
function AddKeyboardEventToShape(shape){
var container = stage.container();
container.tabIndex = 1;
container.focus();
var DELTA = 3;
container.addEventListener('keydown', function (e) {
if (e.keyCode === 37) {
shape.x(shape.x() - DELTA);
} else if (e.keyCode === 38) {
shape.y(shape.y() - DELTA);
} else if (e.keyCode === 39) {
shape.x(shape.x() + DELTA);
} else if (e.keyCode === 40) {
shape.y(shape.y() + DELTA);
} else {
return;
}
e.preventDefault();
});
}
</script>
It is working for me.
1-Remove the function code AddKeyboardEventToShape
2-Remove the code below.
stage.on('mousemove', function (e) {
var container = stage.container();
container.tabIndex = 0;
container.focus(false);
container.off('keydown');
container.removeEventListener('keydown', function (e) {
e.preventDefault();
});
return;
});
3-Replace the code to replace stage.on('click') by code below
let shapeCliked;
const DELTA = 2;
stage.on('click', function (e) {
if (e.target === stage) {
return;
}
shapeCliked = e.target;
var container = stage.container();
container.tabIndex = 1;
container.focus();
container.addEventListener('keydown', function (e) {
switch(e.keyCode) {
case 37:
shapeCliked.x(shapeCliked.x() - DELTA);
break;
case 38:
shapeCliked.y(shapeCliked.y() - DELTA);
break;
case 39:
shapeCliked.x(shapeCliked.x() + DELTA);
break;
case 40:
shapeCliked.y(shapeCliked.y() + DELTA);
break;
default:
return;
}
e.preventDefault();
});
});
So i'm using Konvajs, to draw segments, only vertical and horizontal. My problem is the following, when i start the debug, if the window is small and then i click to maximize, the layer will stay with same size as when small. Ex:
here it s the Javascript file for the Konva creation:
function setUpDesignMap(){
var width = $('#designContainer').width();
var height = $('#designContainer').height();
var blockSnapSize = gridSize;
var isDrawing = false;
var drawShape = null;
designStage = new Konva.Stage({
container: 'designContainer',
width: width,
height: height,
draggable: true,
name:'designStage'
// dragBoundFunc: function(pos) {
// var newY = pos.y < 0 ? 0 : pos.y;
// var newX = pos.x < 0 ? 0 : pos.x;
// return {
// x: newX,
// y: newY
// };
// }
});
/*Set up grid*/
var gridLayer = new Konva.Layer();
var tipLayer = new Konva.Layer();
drawLayer = new Konva.Layer();
segGrp = new Konva.Group({name:'segments'});
/* draw grid */
for (var i = 0; i < 240; i++) {
gridLayer.add(new Konva.Line({
points: [Math.round(i * blockSnapSize), 0, Math.round(i * blockSnapSize), 120*blockSnapSize],
stroke: '#888',
strokeWidth: 0.5,
}));
}
gridLayer.add(new Konva.Line({points: [0,0,10,10]}));
for (var j = 0; j < 120; j++) {
gridLayer.add(new Konva.Line({
points: [0, Math.round(j * blockSnapSize), 240*blockSnapSize, Math.round(j * blockSnapSize)],
stroke: '#888',
strokeWidth: 0.5,
}));
}
/* Stage initial position*/
zoomVars_design = {scale: 1, factor: 1.1, origin: {x:-100*gridSize,y:-50*gridSize}};
designStage.position(zoomVars_design.origin);
designStage.scale({ x: 1, y: 1 });
/*Set up mouse tip*/
var mouseTip = new Konva.Rect({
width: 6,
height: 6,
opacity:0,
fill: '#FFCC00',
stroke: '#FFCC00'
});
tipLayer.add(mouseTip);
/* Set up length indicator */
var lenShape = new Konva.Line({
points:[],
opacity: 1,
strokeWidth: 1,
stroke: '#000',
dash:[7,5]
});
gridLayer.add(lenShape);
/* Set up length text*/
var lenText = new Konva.Text({
align: 'center',
verticalAlign: 'middle',
fontSize: 12
});
gridLayer.add(lenText);
var lenSide = new Konva.Line({
points:[],
opacity: 1,
strokeWidth: 1,
stroke: '#000',
dash:[7,5]
});
gridLayer.add(lenSide);
/*Mouse handlers*/
//remove default behaviour for the container
$("#designContainer").on('mousedown', function(e){
e.preventDefault();
});
$("#designContainer").on('contextmenu', function(e){
e.preventDefault();
});
//mouse handlers on stage
designStage.on('contentMousedown', function (e) {
if(e.evt.button == 0){
designStage.draggable(false);
}
else{
designStage.draggable(true);
return;
}
if(mouseMode == 0){ //draw mode
var startPoint = {x:(mouseTip.attrs.x+3), y:(mouseTip.attrs.y+3)};
if(!isDrawing){
if(!isIntersection(startPoint)){ //cannot be intersection to avoid crosses
//check if there's an intersection on the begining
if(isCorner(startPoint)){
intersectingSeg = false;
intersectingCorner = true;
console.log('intersectingSeg = false')
}
else{
//check if its on an existing segment
var isonseg = isOnSegment(startPoint);
if(isonseg.b){
//validate resulting segments length
var intercected = getSegmentsArray(isonseg.d)[isonseg.i];
var res = breakSegAtIntersection(startPoint,intercected);
if(isValidLength(res[0].start,res[0].end) && isValidLength(res[1].start,res[1].end)){
intersectingSeg = true;
intersectingCorner = false;
console.log('>>>>>>>Intersecting Segment at start')
}
else{
consoleAdd('Resulting segments are too small to you');
return;
}
}
}
//start drawing
drawShape = new Konva.Line({
points: [startPoint.x, startPoint.y],
strokeWidth: 15,
stroke: 'black',
opacity: 0.5,
dir:'h'
});
drawShape.on('mouseover', function (e) {
if(mouseMode == 1){
this.stroke('#031C4D');
drawLayer.draw();
}
});
drawShape.on('mouseout', function (e) {
if(mouseMode == 1){
this.stroke('black');
drawLayer.draw();
}
});
drawShape.on('mouseup', function (e) {
if(mouseMode == 1){
this.stroke('#092C70');
drawLayer.draw();
}
});
segGrp.add(drawShape);
drawLayer.add(segGrp);
drawLayer.draw();
isDrawing = true;
}
else{
consoleAdd('Cannot start on an intersection');
}
gridLayer.draw();
}
}
});
So i want the layer not to be that small, always refitting. Thank you all for your attention!
You need to manually resize your stage when the size of container element is changed.
window.addEventListener('resize', () => {
var width = $('#designContainer').width();
var height = $('#designContainer').height();
designStage.width(width);
designStage.height(height);
})
You may also need to apply the scale to the stage.
Take a look into related demo: https://konvajs.org/docs/sandbox/Responsive_Canvas.html
I am using FabricJS to draw circle in canvas:
var circle = new fabric.Circle({radius: 100,
fill: '',
stroke: 'red',
strokeWidth: 3,
originX: 'center',
originY: 'center'
});
var text = new fabric.Text('HELLO WORLD.',
{ fontSize: 30,
originX: 'center',
originY: 'center',
fill : 'red'
});
var group = new fabric.Group([ circle, text ], {
left: 150, top: 100
});
canvas.add(group);
This code draws a normal circle but I need to freely draw circle with mouse.
Any code help will be appreciated.
According to your previous code for drawing rectangle http://jsfiddle.net/Subhasish2015/8u1cqasa/2/ Here is the code for drawing circle:
$(document).ready(function(){
//Getting the canvas
var canvas1 = new fabric.Canvas("canvas2");
var freeDrawing = true;
var divPos = {};
var offset = $("#canvas2").offset();
$(document).mousemove(function(e){
divPos = {
left: e.pageX - offset.left,
top: e.pageY - offset.top
};
});
$('#2').click(function(){
//Declaring the variables
var isMouseDown=false;
var refCircle;
//Setting the mouse events
canvas1.on('mouse:down',function(event){
isMouseDown=true;
if(freeDrawing) {
var circle=new fabric.Circle({
left:divPos.left,
top:divPos.top,
radius:0,
stroke:'red',
strokeWidth:3,
fill:''
});
canvas1.add(circle);
refCircle=circle; //**Reference of rectangle object
}
});
canvas1.on('mouse:move', function(event){
if(!isMouseDown)
{
return;
}
//Getting yhe mouse Co-ordinates
if(freeDrawing) {
var posX=divPos.left;
var posY=divPos.top;
refCircle.set('radius',Math.abs((posX-refCircle.get('left'))));
canvas1.renderAll();
}
});
canvas1.on('mouse:up',function(){
canvas1.add(refCircle);
//alert("mouse up!");
isMouseDown=false;
//freeDrawing=false; // **Disables line drawing
});
});
});
var Circle = (function() {
function Circle(canvas) {
this.canvas = canvas;
this.className = 'Circle';
this.isDrawing = false;
this.bindEvents();
}
Circle.prototype.bindEvents = function() {
var inst = this;
inst.canvas.on('mouse:down', function(o) {
inst.onMouseDown(o);
});
inst.canvas.on('mouse:move', function(o) {
inst.onMouseMove(o);
});
inst.canvas.on('mouse:up', function(o) {
inst.onMouseUp(o);
});
inst.canvas.on('object:moving', function(o) {
inst.disable();
})
}
Circle.prototype.onMouseUp = function(o) {
var inst = this;
inst.disable();
};
Circle.prototype.onMouseMove = function(o) {
var inst = this;
if (!inst.isEnable()) {
return;
}
var pointer = inst.canvas.getPointer(o.e);
var activeObj = inst.canvas.getActiveObject();
activeObj.stroke = 'red',
activeObj.strokeWidth = 5;
activeObj.fill = 'red';
if (origX > pointer.x) {
activeObj.set({
left: Math.abs(pointer.x)
});
}
if (origY > pointer.y) {
activeObj.set({
top: Math.abs(pointer.y)
});
}
activeObj.set({
rx: Math.abs(origX - pointer.x) / 2
});
activeObj.set({
ry: Math.abs(origY - pointer.y) / 2
});
activeObj.setCoords();
inst.canvas.renderAll();
};
Circle.prototype.onMouseDown = function(o) {
var inst = this;
inst.enable();
var pointer = inst.canvas.getPointer(o.e);
origX = pointer.x;
origY = pointer.y;
var ellipse = new fabric.Ellipse({
top: origY,
left: origX,
rx: 0,
ry: 0,
transparentCorners: false,
hasBorders: false,
hasControls: false
});
inst.canvas.add(ellipse).setActiveObject(ellipse);
};
Circle.prototype.isEnable = function() {
return this.isDrawing;
}
Circle.prototype.enable = function() {
this.isDrawing = true;
}
Circle.prototype.disable = function() {
this.isDrawing = false;
}
return Circle;
}());
var canvas = new fabric.Canvas('canvas');
var circle = new Circle(canvas);
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.17/fabric.min.js"></script>
Please draw circle here
<div id="canvasContainer">
<canvas id="canvas" width="400" height="400" style="border: solid 1px"></canvas>
</div>
Here is the detail blog with jsfiddle - https://blog.thirdrocktechkno.com/sketching-circle-of-a-html5-canvas-using-the-fabricjs-f7dbfa20cf2d
Here is an example of drawing a rectangle which I carefully made and works for latest versions. Krunan example seems to work OK- just in case this is a rectangle free drawing implementation that doesn't use DOM apis like e.clientX, offsetLeft, etc to track the coords, but fabric.js APIs only which I think is safer. Also unregister event listeners - I'm still trying to refine it since I need free drawing support for my project - Since there is no official support for this I wanted to reference the example here for others.
https://cancerberosgx.github.io/demos/misc/fabricRectangleFreeDrawing.html
An easy way to add a Circle to a canvas:
canvas.add(new fabric.Circle({ radius: 30, fill: "green", top: 100, left: 100 }));
I am trying to recreate the game http://www.sinuousgame.com/ and started studying html5 canvas and kineticJS.
Recently i came across the getIntersection function and coudnt find much details regarding it.But with what i had ,i did make a code to get the Collision detection done using getIntersection() function.
But it doesnt seem to be working.
As you can see, My Fiddle: http://jsfiddle.net/p9fnq/8/
//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
});
var line = new Kinetic.Line({
points: [],
stroke: 'cyan',
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);
});
var x = 0;
var y = 0;
var noOfEnemies = 200;
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.5 + Math.random() * 50);
enemyArmada.push(enemy);
layer.add(enemy);
}
}
var checkCollide = function() {
var position = stage.getPointerPosition();
if(position == null)
position = player.position();
if(position == null)
position = {x:0,y:0};
var collided = stage.getIntersection(position);
console.log(position);
if (typeof collided !== 'Kinetic.Shape') {
console.log("not shape");
}
else {
console.log("BOOOM!!!");
}
};
var anim = new Kinetic.Animation(function(frame) {
checkCollide();
for (var i = 0; i < noOfEnemies; i++) {
var e = enemyArmada[i];
e.position({
x: e.position().x - e.speedX * (frame.timeDiff / 400),
y: e.position().y + e.speedY * (frame.timeDiff / 400)
});
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();
I need the collision to be detected. The function i have written here is checkCollide and its called within the kinetic.Animation function.
Can anyone help me out with this??
(If you don't know the solution,please do like the post,i need the solution badly)
The source of the problem
getIntersection(point) means "is any object at this point".
Since the point you're using is the player's position, getIntersection will always return true because player is always at its own position !
One solution
Put your player on one layer and all enemies on a separate layer.
That way you can hit test the enemy layer without the interference of the player object.
Code and a Demo: http://jsfiddle.net/m1erickson/JCfW8/
<!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-v5.0.1.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 enemyLayer = new Kinetic.Layer();
stage.add(enemyLayer);
var playerLayer = new Kinetic.Layer();
stage.add(playerLayer);
var player = new Kinetic.Circle({
x:100,
y:100,
radius: 10,
fill: 'green',
draggable: true
});
player.on("dragmove",function(){
if(enemyLayer.getIntersection(player.position())){
this.fill("red");
playerLayer.draw();
}
});
playerLayer.add(player);
playerLayer.draw();
var enemy = new Kinetic.Circle({
x:200,
y:100,
radius: 20,
fill: 'blue',
draggable: true
});
enemyLayer.add(enemy);
enemyLayer.draw();
}); // end $(function(){});
</script>
</head>
<body>
<h4>Drag the green player<br>Player will turn red if it collides<br>with the blue enemy</h4>
<div id="container"></div>
</body>
</html>
Another solution
Mathematically test the player against every enemy:
Warning: untested code--some tweaking might be required
function playerEnemyCollide(){
var playerX=player.x();
var playerY=player.y();
var playerRadius=player.radius();
for(var i=0;i<enemyArmada.length;i++){
var e=enemyArmada[i];
if(circlesColliding(playerX,playerY,playerRadius,e.x,e.y,e.radius)){
return(true);
}
}
return(false);
}
function circlesColliding(cx1,cy1,radius1,cx2,cy2,radius2){
var dx=cx2-cx1;
var dy=cy2-cy1;
return(dx*dx+dy*dy<(radius1*2+radius2*2);
}
The code below creates a scalable and draggable triangle with anchor points at its vertices. i want that the anchor points should only visible when mouse goes over them??
and also, how collision detection can be implemented to avoid drawing of other spaces inside the triangle?
<html>
<head>
<script src="http://www.html5canvastutorials.com/libraries/kinetic-v3.10.0.js"></script>
<script type="text/javascript">
// the circle anchor points
function buildAnchor(layer, x, y, name) {
var anchor = new Kinetic.Circle({
x: x,
y: y,
radius: 6,
stroke: "#666",
fill: "#ddd",
strokeWidth: 2,
draggable: true,
name : name
});
// add hover styling
anchor.on("mouseover", function() {
document.body.style.cursor = "pointer";
this.setStrokeWidth(4);
layer.draw();
});
anchor.on("mouseout", function() {
document.body.style.cursor = "default";
this.setStrokeWidth(2);
layer.draw();
});
layer.add(anchor);
return anchor;
}
function buildTriangle(layer, points, name) {
var triangle = new Kinetic.Polygon({
stroke : "red",
strokeWidth : 4,
name : name,
draggable : true
});
triangle.a = buildAnchor(layer, points[0], points[1], "anchor");
triangle.b = buildAnchor(layer, points[2], points[3], "anchor");
triangle.c = buildAnchor(layer, points[4], points[5], "anchor");
triangle.was = { x : 0, y : 0 };
layer.add(triangle);
return triangle;
}
function drawTriangle() {
var triangle = this.get(".triangle")[0];
if ( !triangle.isDragging() ) {
triangle.setPoints([ triangle.a.attrs.x - triangle.was.x,
triangle.a.attrs.y - triangle.was.y,
triangle.b.attrs.x - triangle.was.x,
triangle.b.attrs.y - triangle.was.y,
triangle.c.attrs.x - triangle.was.x,
triangle.c.attrs.y - triangle.was.y ]);
} else {
var anchors = this.get(".anchor");
for ( var i = 0; i < anchors.length; i ++ ) {
anchors[i].setX(anchors[i].getX() + (triangle.getX() - triangle.was.x));
anchors[i].setY(anchors[i].getY() + (triangle.getY() - triangle.was.y));
}
triangle.was.x = triangle.getX();
triangle.was.y = triangle.getY();
}
}
window.onload = function() {
var stage = new Kinetic.Stage({
container: "container",
height: 200
});
var layer = new Kinetic.Layer({
drawFunc : drawTriangle
});
var triangle = buildTriangle(layer, [60, 100, 90, 100, 90, 140], "triangle");
triangle.moveToBottom();
// add the layer to the stage
stage.add(layer);
}
</script>
<style>
#container {
border: 1px solid black;
}
</style>
</head>
<body onmousedown="return false;">
<div id="container"></div>
</body>
</html>
jsFiddle: http://jsfiddle.net/Y9AtR/
I like #Tomalak's solution, here is mine:
http://jsfiddle.net/Y9AtR/2/
triangle.on('mouseover', function(){
triangle.a.show();
triangle.b.show();
triangle.c.show();
layer.draw();
});
triangle.on('mouseout', function(){
//if( not near triangle ) // add some logic so that they don't disappear right away, maybe use distance formula?
triangle.a.hide();
triangle.b.hide();
triangle.c.hide();
layer.draw();
})