I'm working on a board game with kineticjs and I'm facing a problem with mouse handling.
I have an image with a mousemove event that draw a preview selection.
The problem is with the click event on the same image that is firing only 1 on 9 times..
If I remove the on_mousemove the on_click is working perfectly..
Anyone has an explanation and/or workaround ?
Thanks
Edit
Fiddle link: http://fiddle.jshell.net/gTuCE/12/
Your code was a bit messy so I cleaned it up and it's working now: jsfiddle
In your function createSquareItem(), squareLayer was undefined.
You only have to add Kinetic.Layers once. In both your createSquareItem createTemporarySquareItems functions, you were adding mainLayer to the stage every time you call the function. This is wrong since you already added mainLayer to the stage earlier.
In your createTemporarySquareItems function, I had to add mainLayer.drawScene() and in createSquareItem I had to add mainLayer.draw()
function createSquareItem(point, color) {
var boardPoint = point;
var rect = new Kinetic.Rect({
x: boardPoint.x,
y: boardPoint.y,
width: 18,
height: 18,
fill: color,
stroke: 'black',
strokeWidth: 0
});
mainLayer.add(rect);
//squareLayer.drawScene(); //squareLayer is undefined.
mainLayer.draw();
}
function createTemporarySquareItems(point, cleanLayer) {
if (cleanLayer == true) {
do {
var r = tempSquareArray.pop();
if (r != null) {
//tempSquareLayer.remove(r);
r.destroy();
}
} while (r != null);
}
var boardPoint = point;
var rect = new Kinetic.Rect({
x: boardPoint.x,
y: boardPoint.y,
width: 18,
height: 18,
fill: 'orange',
stroke: null,
strokeWidth: 0
});
tempSquareArray.push(rect);
mainLayer.add(rect);
mainLayer.drawScene();
}
For more information on KineticJS' draw methods, see here: What is the difference between KineticJS draw methods?
Related
in my Highcharts project, I successfully make all the shapes in a single annotation draggable, but when I add the SVG (the type of this shape is "path"), the SVG doesn't move along with other shapes in the annotation.
I need to have some customised shapes in the annotation. Can anyone point out what the issue is for this SVG? Is it possible to put the SVG within annotation and still be draggable? Or is it some mistake I made that causes the issue?
My example here. https://jsfiddle.net/roy_jaide/754xuhtk/ As you can see, the label, circle and the line are all draggable, but the SVG shape just doesn't move at all.
Thanks for reading my question, and much appreciated if any solution provided.
Highcharts.Annotation.prototype.onDrag = function (e) {
if (this.chart.isInsidePlot(e.chartX - this.chart.plotLeft, e.chartY - this.chart.plotTop)) {
var translation = this.mouseMoveToTranslation(e),
xAxis = this.chart.xAxis[0],
yAxis = this.chart.yAxis[0],
xStep = this.options.stepX,
yStep = this.options.stepY,
pxStep = xAxis.toPixels(xStep) - xAxis.toPixels(0),
pyStep = yAxis.toPixels(yStep) - yAxis.toPixels(0);
if (this.options.draggable === 'x') { //for now, it's exclusive for age handle
this.potentialTranslationX += translation.x;
if (Math.abs(this.potentialTranslationX) >= Math.abs(pxStep)) {
translation.x = (this.potentialTranslationX > 0) ? pxStep : -pxStep;
translation.y = 0;
this.currentXValue += (this.potentialTranslationX > 0) ? xStep : -xStep;
this.potentialTranslationX -= (this.potentialTranslationX > 0) ? pxStep : -pxStep; //minus the step and continue to cumulate
//this.potentialTranslation = 0; //not correct, the mouse will go faster than the handle
if (this.points.length) {
this.translate(translation.x, 0);
} else {
this.shapes.forEach(function (shape) {
shape.translate(translation.x, 0);
});
this.labels.forEach(function (label) {
label.translate(translation.x, 0);
label.text = label.annotation.options.preText + label.annotation.currentXValue;
});
}
}
}
this.redraw(false);
}
}
Update 1: After trying Sebastian's answer on my chart, it turns out to be difficult to calculate the correct coordinates. At last I use type "image" to put display the shape. The shape is a Font-Awesome icon so before using "image" I did try to add a label with "useHTML" : true, but it seems the icon is moved a little after the first redraw(false), not sure why.
The image of the shape. I achieved this by adding "image" shape.
d: ["M", 440, 72, "L", 410, 45, 470, 45, "Z"],
I wouldn't recommend this way to create a draggable custom shape. This option creates a shape as expected but also sets a fixed position. Probably it is possible to implement move functionality, but I think that it will require a lot of changes into draggable core code.
What I can suggest is to make it this way:
annotations: [{
draggable: 'x',
shapes: [{
points: [{
x: 440,
y: 72
}, {
x: 410,
y: 45
}, {
x: 470,
y: 45
}, {
x: 440,
y: 72
}],
fill: 'red',
type: 'path',
stroke: "blue",
strokeWidth: 3,
markerStart: 'circle',
}]
}]
Where markerStart is a defined shape.
See a Demo
I am trying to do something like paint with KineticJS. I am trying to draw the color with circles that originate from the mouse position. However the eventlistener of the mouse position seems too slow and when I move the mouse too fast the circles drawn are far from each other resulting this:
I have seen people filling array with points drawing lines between them, but I thought thats very bad for optimization because after dubbing the screen too much the canvas starts lagging because it has too much lines that it redraws every frame. I decided to cancel the cleaning of the layer and I am adding new circle at the current mouse position and I remove the old one for optimization. However since Im not drawing lines on fast mouse movement it leaves huge gaps. I would be very grateful if anyone can help me with this.
Here is my code:
(function() {
var stage = new Kinetic.Stage({
container: 'main-drawing-window',
width: 920,
height: 750
}),
workplace = document.getElementById('main-drawing-window'),
layer = new Kinetic.Layer({
clearBeforeDraw: false
}),
border = new Kinetic.Rect({
stroke: "black",
strokeWidth: 2,
x: 0,
y: 0,
width: stage.getWidth(),
height: stage.getHeight()
}),
brush = new Kinetic.Circle({
radius: 20,
fill: 'red',
strokeWidth: 2,
x: 100,
y: 300
});
Input = function() {
this.mouseIsDown = false;
this.mouseX = 0;
this.mouseY = 0;
this.offsetX = 0;
this.offsetY = 0;
};
var input = new Input();
document.documentElement.onmousedown = function(ev) {
input.mouseIsDown = true;
};
document.documentElement.onmouseup = function(ev) {
input.mouseIsDown = false;
};
document.documentElement.onmousemove = function(ev) {
ev = ev || window.event;
// input.mouseX = (ev.clientX - workplace.offsetLeft);
// input.mouseY = (ev.clientY - workplace.offsetTop);
input.mouseX = (ev.offsetX);
input.mouseY = (ev.offsetY);
};
function DistanceBetweenPoints(x1, y1, x2, y2) {
return Math.sqrt(((x2 - x1) * (x2 - x1)) + ((y2 - y1) * (y2 - y1)));
}
var canvasDraw = setInterval(function() {
// console.log(input);
if (input.mouseIsDown) {
workplace.style.cursor = "crosshair";
var currentBrushPosition = brush.clone();
currentBrushPosition.setX(input.mouseX);
currentBrushPosition.setY(input.mouseY);
// var distance = DistanceBetweenPoints(brush.getX(), brush.getY(), currentBrushPosition.getX(), currentBrushPosition.getY());
// if (distance > brush.getRadius() * 2) {
// var fillingLine = new Kinetic.Line({
// points: [brush.getX(), brush.getY(), currentBrushPosition.getX(), currentBrushPosition.getY()],
// stroke: 'yellow',
// strokeWidth: brush.getRadius()*2,
// lineJoin: 'round'
// });
// // layer.add(fillingLine);
// }
layer.add(currentBrushPosition);
brush.remove();
brush = currentBrushPosition;
layer.draw();
// if (fillingLine) {
// fillingLine.remove();
// }
}
if (!input.mouseIsDown) {
workplace.style.cursor = 'default';
}
}, 16);
layer.add(border);
stage.add(layer);
})();
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Coloring Game</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/kineticjs/5.2.0/kinetic.min.js"></script>
</head>
<body>
<div id="main-drawing-window"></div>
<script type="text/javascript" src="./JS files/canvas-draw.js"></script>
</body>
</html>
Don't use individual Kinetic.Circles for each mousemove. Every Kinetic object is a "managed" object and that management takes up a lot of resources. KineticJS will slow to a crawl as the number of circles increases with every mousemove.
Instead, use a Kinetic.Shape and draw you circles onto the canvas with
// This is Pseudo-code since I haven't worked with KineticJS in a while
shapeContext.beginPath();
shapeContext.arc(mouseX,mouseY,20,0,Math.PI*2);
shapeContext.fillStrokeShape(this);
This will probably clear your problem, but if the mouse is moved very far in a single mousemove then you might have to draw a lineTo (instead of arc) between the last mouse point and the current far-away mouse point.
I have a circle added to a layer. In the top of the layer I added a text. I would like to run an animation when the mouse is over the circle, but when the mouse reaches the text the mouseout callback function is called. How can I prevent that?
var circle = new Kinetic.Circle({
x: j * xcenterstep + xshift,
y: i * ycenterstep + yshift,
radius: t_radius,
fill: t_fill,
stroke: t_stroke,
strokeWidth: t_stroke_w,
strokeOpacity: 0.1,
opacity: 0.3 + t_number * 0.05,
});
if (t_number) {
circle.tw;
circle.on("mouseover", function () {
this.tw = new Kinetic.Tween({
node: this,
duration: 0.3,
strokeWidth: 6
});
this.tw.play();
});
circle.on("mouseout", function () {
this.tw.reverse();
});
}
// Adding the text
var radiusText = new Kinetic.Text({
x : circle.getX(),
y : circle.getY(),
text : t_number,
fontSize : radius,
fill : '#fff',
fontStyle: 'bold',
align : 'center'
});
radiusText.setOffset({
x : radiusText.getWidth()/2,
y : radiusText.getHeight()/2
});
bgLayer.add(circle);
bgLayer.add(radiusText);
I think it is better to use mouseenter event. You can disable text's events to prevent mouseout from circle.
radiusText.listening(false)
Reviewing your code, you were missing a } to close the if (t_number) {. I am not sure if it was supposed to encompass the mouseover and mouseout events, but it might have caused your code to respond differently than you are expecting.
Being new to Javascript, my understanding of this is a bit shaky. I've read a few articles and SO posts and learned quite a bit, but I'm having issues implementing some code. I'm using the KineticJS library to implement some canvas functions. I was working with a fiddle and was able to get an image to resize with the mouse control, however, when I put the code into a prototype function, resizing no longer works.
Canvas.prototype.addImg = function(){
var self = this;
var image;
var imageObj = new Image();
imageObj.onload = function() {
image = new Kinetic.Image({
x: 200,
y: 50,
image: imageObj,
width: 106,
height: 118,
draggable: false
});
self.backgroundLayer.add(image);
self.stage.add(self.backgroundLayer);
};
imageObj.src = 'http://www.html5canvastutorials.com/demos/assets/yoda.jpg';
var circle1 = new Kinetic.Circle({
x: 150,
y: 150,
radius: 10,
fill: 'red',
stroke: 'black',
strokeWidth: 4,
draggable: false
});
circle1.isResizing = false;
circle1.on("click", function (e) {
// toggle resizing true/false
var isResizing = !this.isResizing;
this.setDraggable(isResizing);
self.backgroundLayer.setDraggable(!isResizing);
this.setFill((isResizing ? "green" : "red"));
this.isResizing = isResizing;
self.backgroundLayer.draw();
});
circle1.on("dragmove", function () {
if (this.isResizing) {
var pos = this.getPosition();
var x = pos.x;
var y = pos.y;
var rectX = image.getX();
var rectY = image.getY();
image.setSize(x - rectX, y - rectY);
self.backgroundLayer.draw();
}
});
self.backgroundLayer.add(circle1);
self.backgroundLayer.draw();
}
I am assuming the problem lies within the use of this in the function, but I'm not sure how to fix the problem. Could somebody tell me what the problem is and how I would fix this?
I can see a problem with the line that is setting the size of image:
image.setSize(x - rectX, y - rectY);
For example if x is 100 and rectX is 200, you end up with a width of '-100', which is not legal.
In the fiddle you provided, when I use constant values, the image re-sizes perfectly:
rect.setSize(200, 200);
Modified fiddle.
The solution I've come upon, is that it is not an issue of this, but the setSize() method. For some reason or another, it is not working in my local application. When I replace this for setWidth() and setHeight(), everything works the way that it should.
You can interact with this code here on jsFiddle
In the fiddle you can see that I have made a flag (Kinetic.Rect) on a flagpole (Kinetic.Line). I desire to fire an event when the user moves the mouse over any portion of the flag or flagpole. In prior attempts I have attached event handlers to each shape individually, only to learn that Kinetic.Line does not fire events.
In this latest attempt I added the shapes to a group and attached the handler to the group thinking this would solve the issue: it does not.
Is there any way to achieve the desired behavior? Thank you, and remember to press F12 to see the handler's console messages.
var handler = function(e) {
console.log("Event fired.");
};
var stage = new Kinetic.Stage({
container: 'testBlock',
width: 200,
height: 200
});
var layer = new Kinetic.Layer();
var group = new Kinetic.Group();
var rect = new Kinetic.Rect({
x: 75,
y: 10,
width: 50,
height: 50,
fill: 'silver',
});
line = new Kinetic.Line({
points: [
{x: 125, y: 10},
{x: 125, y: 160},
],
stroke: 'black',
strokeWidth: 1
});
// add the shapes to the group
group.add(rect);
group.add(line);
// event handler for the group
group.on("mouseover", handler);
// add the group to the layer
layer.add(group);
// add the layer to the stage
stage.add(layer);
Kinetic.Line's have trouble with events when the stroke is too small, you can see this evident with any line with stroke < 3px.
This was the response I got from Eric Rowell (creator of KineticJS):
yep, KineticJS ignores the anti-aliased pixels. If you're drawing a 1px diagonal line, and you want it to be detectable, you need to create a custom hit function to define the hit region. You probably will want to create a hit region that's a line which is about 5px thick or so. Here's an example on creating custom hit regions:
http://www.html5canvastutorials.com/kineticjs/html5-canvas-kineticjs-custom-hit-function-tutorial/
So in addition to Ani's answer, you can also use the drawHitFunc property to make a custom hit region for the line that is thicker than the actual line:
line = new Kinetic.Line({
points: [
{x: 125, y: 10},
{x: 125, y: 160},
],
stroke: 'black',
strokeWidth: 1,
drawHitFunc: function(canvas) {
var x1=this.getPoints()[0].x;
var x2=this.getPoints()[1].x;
var y1=this.getPoints()[0].y;
var y2=this.getPoints()[1].y;
var ctx = canvas.getContext();
ctx.beginPath();
ctx.lineWidth = 1;
ctx.moveTo(x1-3,y1-3);
ctx.lineTo(x1-3,y2+3);
ctx.lineTo(x2+3,y2+3);
ctx.lineTo(x2+3,y1-3);
ctx.closePath();
canvas.fillStroke(this);
}
});
jsfiddle
Try this fiddle
I'm using Kinetic.Rect with width=1 and height= y2-y1 of your line.
line = new Kinetic.Rect({
x: 125, y: 10,
width: 1, height: 150,
fill: 'black',
});