kineticjs group cache and layer draw is hiding kinetic arc shapes - javascript

I am creating a circle as a group of kinetic arcs. When I cache the group and subsequently call the draw function on the layer, three quarters of the circle are hidden. I think layer.draw may require an offset but really I'm only guessing. When I remove the fill, stroke or opacity from the arc or the object literal from the cache call then the full circle is displayed. http://jsfiddle.net/leydar/gm2FT/5/ Any insights gratefully received.
function createArc(n){
var arc = new Kinetic.Arc({
innerRadius: 30,
outerRadius: 50,
/* if I remove the fill, stroke or opacity
the full wheel is correctly displayed */
fill: 'blue',
stroke: 'black',
opacity: 0.3,
strokeWidth: 1,
angle: 36,
rotation: 36*n
});
return arc;
}
function init() {
var arc;
var stage = new Kinetic.Stage({
container: 'container',
width: 104,
height: 104
});
var layer = new Kinetic.Layer();
var circle = new Kinetic.Group();
for(var i=0;i<10;i++) {
arc = createArc(i);
circle.add(arc);
};
layer.add(circle);
stage.add(layer);
/* if I do not cache or do not call layer.draw()
then again the wheel is correctly displayed */
circle.cache({
x: -52,
y: -52,
width: 104,
height: 104,
drawBorder: true
});
layer.draw();
}
init();
Stephen

This is a bug of KineticJS.
You may use this workaround:
Kinetic.Arc.prototype._useBufferCanvas = function() {
return false;
};
http://jsfiddle.net/gm2FT/6/

Related

KonvaJS - Rotate rectangle around cursor without using offset

I am using KonvaJS to drag and drop rectangles into predefined slots. Some of the slots need to be rotated 90 degrees. I have a hit box around the slots that are rotated vertically, so when the user drags the rectangle into the area it will rotate 90 degrees automatically (to match the orientation). When it rotates, it moves out from under the mouse. This can be solved with offset, but then the rectangle doesn't visually line up with the boxes after snapping. This can (probably) be solved with additional code.
I have tried to rotate the rectangle, and then move it under the mouse. Since the user is still dragging it, this doesn't seem to work as I planned.
Is it possible to force the rectangle to rotate under the mouse without using offset?
Here is a fiddle showing the issue - The offset problems can be demonstrated by setting the first variable to true.
https://jsfiddle.net/ChaseRains/1k0aqs2j/78/
var width = window.innerWidth;
var height = window.innerHeight;
var rectangleLayer = new Konva.Layer();
var holdingSlotsLayer = new Konva.Layer();
var controlLayer = new Konva.Layer();
var stage = new Konva.Stage({
container: 'container',
width: width,
height: height,
draggable: true
});
//vertical holding spot
holdingSlotsLayer.add(new Konva.Rect({
x: 300,
y: 25,
width: 130,
height: 25,
fill: '#fff',
draggable: false,
rotation: 90,
stroke: '#000'
}));
//horizontal holding spot
holdingSlotsLayer.add(new Konva.Rect({
x: 25,
y: 75,
width: 130,
height: 25,
fill: '#fff',
draggable: false,
rotation: 0,
stroke: '#000'
}));
//mask to set boundaries around where we wannt to flip the rectangle
controlLayer.add(new Konva.Rect({
x: 215,
y: 15,
width: 150,
height: 150,
fill: '#fff',
draggable: false,
name: 'A',
opacity: 0.5
}));
stage.add(holdingSlotsLayer, controlLayer);
//function for finding intersections
function haveIntersection(placeHolder, rectangle, zone) {
if (rectangle.rotation == 0 || zone == true) {
return !(
rectangle.x > placeHolder.x + placeHolder.width ||
rectangle.x + rectangle.width < placeHolder.x ||
rectangle.y > placeHolder.y + placeHolder.height ||
rectangle.y + rectangle.height < placeHolder.y
);
} else {
return !(
rectangle.x > placeHolder.x + 25 ||
rectangle.x + rectangle.width < placeHolder.x ||
rectangle.y > placeHolder.y + placeHolder.height + 90 ||
rectangle.y + rectangle.height < placeHolder.y
);
}
}
//function to create rectangle group (so we can place text on the rectangle)
function spawnRectangle(angle) {
var rectangleGroup = new Konva.Group({
x: 95,
y: 95,
width: 130,
height: 25,
rotation: angle,
draggable: true,
});
rectangleGroup.add(new Konva.Rect({
width: 130,
height: 25,
fill: 'lightblue'
}));
rectangleGroup.add(new Konva.Text({
text: '123',
fontSize: 18,
fontFamily: 'Calibri',
fill: '#000',
width: 130,
padding: 5,
align: 'center'
}));
//function tied to an on drag move event
rectangleGroup.on('dragmove', (e) => {
//shrink rectangle hitbox for use in placeholder intersection
var dimensions = {
"height": 3,
"width": 5,
"x": e.target.attrs.x,
"y": e.target.attrs.y,
'rotation': e.target.attrs.rotation
};
//loop over holding slots to see if there is an intersection.
for (var i = 0; holdingSlotsLayer.children.length > i; i++) {
//if true, change the look of the slot we are hovering
if (haveIntersection(holdingSlotsLayer.children[i].attrs, dimensions, false)) {
holdingSlotsLayer.children[i].attrs.fill = '#C41230';
holdingSlotsLayer.children[i].attrs.dash = [10, 3];
holdingSlotsLayer.children[i].attrs.stroke = '#000';
//set attributes back to normal otherwise
} else {
holdingSlotsLayer.children[i].attrs.fill = '#fff';
holdingSlotsLayer.children[i].attrs.dash = null;
holdingSlotsLayer.children[i].attrs.stroke = null;
}
}
//check to see if we are in a zone that requires the rectangle to be flipped 90 degrees
if (haveIntersection(controlLayer.children[0].attrs, dimensions, true)) {
if (rectangleGroup.attrs.rotation != 90) {
rectangleGroup.attrs.rotation = 90;
}
} else {
rectangleGroup.attrs.rotation = 0;
}
stage.batchDraw();
});
rectangleGroup.on('dragend', (e) => {
for (var i = 0; holdingSlotsLayer.children.length > i; i++) {
//If the parking layer has an element that is lit up, then snap to position..
if (holdingSlotsLayer.children[i].attrs.fill == '#C41230') {
rectangleGroup.position({
x: holdingSlotsLayer.children[i].attrs.x,
y: holdingSlotsLayer.children[i].attrs.y
});
holdingSlotsLayer.children[i].attrs.fill = '#fff';
holdingSlotsLayer.children[i].attrs.dash = null;
holdingSlotsLayer.children[i].attrs.stroke = null;
}
}
stage.batchDraw();
});
rectangleLayer.add(rectangleGroup);
stage.add(rectangleLayer);
}
body {
margin: 0;
padding: 0;
overflow: hidden;
background-color: #D3D3D3;
background-size: cover;
}
#desc {
position: absolute;
top: 5px;
left: 5px;
}
<script src="https://unpkg.com/konva#4.0.18/konva.min.js"></script>
<body>
<div id="container"></div>
<div id="desc">
<button onclick="spawnRectangle(0)">spawn rectangle</button>
</div>
</body>
Here is a simple function to rotate the rectangle under the mouse, without using konva offset(). I used a tween to apply the movement but if you prefer to use it without the tween just apply the rect.rotate() then apply the newPos x & y as the position.
EDIT: The OP pointed out that if you clicked, held the mouse down whilst the rectangle completed its animation, then dragged, then the rectangle would jump away. What gives ? Well, when the mousedown event runs Konva takes note of the shape's initial position in its internal drag function. Then when we start to actually drag the mouse, Konva dutifully redraws the shape in the position it calculates. Now, 'we' know that we moved the shape in out code, but we didn't let Konva in on our trick.
The fix is to call
rect.stopDrag();
rect.startDrag();
immediately after the new position has been set. Because I am using a tween I do this in the onFinish() callback function of one of the tweens - you would want to ensure its the final tween if you apply more than one. I got away with it because my tweens run over the same period. If you aren't using tweens, just call the above immediately you apply your last rotate() or position() call on the shape.
function rotateUnderMouse(){
// Get the stage position of the mouse
var mousePos = stage.getPointerPosition();
// get the stage position of the mouse
var shapePos = rect.position();
// compute the vector for the difference
var rel = {x: mousePos.x - shapePos.x, y: mousePos.y - shapePos.y}
// Now apply the rotation
angle = angle + 90;
// and reposition the shape to keep the same point in the shape under the mouse
var newPos = ({x: mousePos.x + rel.y , y: mousePos.y - rel.x})
// Just for fun, a tween to apply the move: See https://konvajs.org/docs/tweens/Linear_Easing.html
var tween1 = new Konva.Tween({
node: rect,
duration: 0.25,
x: newPos.x,
y: newPos.y,
easing: Konva.Easings.Linear,
onFinish: function() { rect.stopDrag(); rect.startDrag();}
});
// and a tween to apply the rotation
tween2 = new Konva.Tween({
node: rect,
duration: 0.25,
rotation: angle,
easing: Konva.Easings.Linear
});
tween2.play();
tween1.play();
}
function setup() {
// Set up a stage and a shape
stage = new Konva.Stage({
container: 'canvas-container',
width: 650,
height: 300
});
layer = new Konva.Layer();
stage.add(layer);
newPos = {x: 80, y: 40};
rect = new Konva.Rect({
width: 140, height: 50, x: newPos.x, y: newPos.y, draggable: true, stroke: 'cyan', fill: 'cyan'
})
layer.add(rect);
stage.draw()
rect.on('mousedown', function(){
rotateUnderMouse()
})
}
var stage, layer, rect, angle = 0;
setup()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/konva/4.0.13/konva.js"></script>
<p>Click the rectangle - it will rotate under the mouse.</p>
<div id="canvas-container"></div>

Fabricjs: How to get the area?

I need to know the area of all elements of the group. Is there a ready-made solution? Perhaps you know the area excluding the imposition?
window.canvas = new fabric.Canvas('fabriccanvas');
var circle1 = new fabric.Circle({
radius: 50,
fill: 'red',
left: 0
});
var Rect = new fabric.Rect({
left: 50,
top: 50,
height: 20,
width: 20,
fill: 'green'
});
var circle2 = new fabric.Circle({
radius: 20,
fill: 'black',
left: 70,
top: 80
});
var group = new fabric.Group([ circle1, circle2, Rect ], {});
window.canvas.add(group);
VINET,
There is no predefined functionality, you have to build your own. This is short example how to calculate area for circles and rectangles in the group (as you created above):
var groupArea = 0;
group.forEachObject(function(o){
groupArea += calculateArea(o);
});
function calculateArea(obj){
switch (obj.type){
case 'circle':
return Math.PI*obj.radius*obj.radius;
break;
case 'rect':
return obj.width*obj.height;
break;
}
}
alert(groupArea);
This post is how to calculate polygon area: Calculating Polygon Area
This post is for triangle area: Calculate triangle area and circumference from user input sides
Hopefully it will help you.

How to get the center point of canvas

How to get The center point of the canvas object/rectangle. I use the Konvajs library for my small project. in the konva documentation said that you need to center the point to get good rotation.
http://konvajs.github.io/docs/animations/Rotation.html
Ex
var yellowRect = new Konva.Rect({
x: 220,
y: 75,
width: 100,
height: 50,
fill: 'yellow',
stroke: 'black',
strokeWidth: 4,
offset: {
x: 50 // how to solve this using formula so it will dynamic,
y: 25 // how to solve this using formula so it will dynamic
}
});
Rotating rectangular objects around their centers
By default, KonvaJS sets the rotation point of a rectangle at its top-left corner. Therefore to rotate from the center of the rectangle you must push the rotation point to the center of the rectangle.
You can do this by setting the offsetX=rectangleWidth/2 and offsetY=rectangleHeight/2
var yellowRectWidth=100;
var yellowRectHeight=50;
var yellowRect = new Konva.Rect({
x: 220,
y: 75,
width: yellowRectWidth,
height: yellowRectHeight,
fill: 'yellow',
stroke: 'black',
strokeWidth: 4,
offset: {
x: yellowRectWidth/2,
y: yellowRectHeight/2
}
});
Rotating circular objects around their centers
By default, KonvaJS sets the rotation point of circular shapes at their centerpoints. Therefore to rotate from the center of circular shapes you won't have to set any offsets.

Drag while in background in KineticJs

I have two layers generally representing a large background and some content on top of it.
I have made the background draggable but when dragged, it covers the content of the other layer.
Is it possible to keep it in the background while dragging it?
I have tried binding the drag events with .moveToBottom() for the background group (later added to backgroundLayer) like that:
groupBackground.on('dragstart',function(){
groupBackground.moveToBottom();
});
groupBackground.on('dragmove',function(){
groupBackground.moveToBottom();
});
groupBackground.on('dragend',function(){
groupBackground.moveToBottom();
});
but to no result.
You can “draw under” by using the canvas “.globalCompositeOperation”
This will allow your user to drag the background under the foreground.
And you can apply it to KineticJs like this:
layer.getContext().globalCompositeOperation = "destination-over";
Here is code and a Fiddle: http://jsfiddle.net/m1erickson/2GFSE/
var stage = new Kinetic.Stage({
container: 'container',
width: 578,
height: 200
});
var layer = new Kinetic.Layer();
stage.add(layer);
var background = new Kinetic.Rect({
x: stage.getWidth() / 2,
y: stage.getHeight() / 2,
width: 250,
height: 250,
fill: 'black',
stroke: 'black',
strokeWidth: 4,
draggable: true
});
var foreground = new Kinetic.Ellipse({
x: stage.getWidth() / 3,
y: stage.getHeight() / 3,
radius: {
x: 50,
y: 30
},
fill: 'red',
stroke: 'black',
strokeWidth: 4
});
// add the background and foreground to the layer
layer.add(foreground);
layer.draw();
layer.getContext().globalCompositeOperation = "destination-over";
layer.add(background);
layer.draw();

KineticJS / Javascript dynamic creation and immediate dragging

What I want do is dynamically create a shape on mousedown, and then immediately have it (the shape) follow the mouse cursor until mouseup sets it in place.
Here is what I have so far and it's not working for me.
addNegativeButton.on('mousedown', function(){
var userPos = stage.getUserPosition();
shapesLayer.add(new Kinetic.Image({
image: imageObj,
x: userPos.x,
y: userPos.y,
height: 25,
width: 25,
rotation: 1,
draggable: true,
offset: 12
}));
var last = shapesLayer.getChildren()[shapesLayer.getChildren().length -1];
stage.on("mouseup", function(){
last.setAbsolutePosition(stage.getUserPosition());
stage.off("mouseup");
});
To reiterate:
What I have is an 'addNegativeButton' which when clicked creates a shape.
But I want it to follow the mouse cursor until the click is released.
http://jsfiddle.net/CPrEe/37/
Any suggestions?
Turns out its rather simple ;)
After you add the element/shape, all you have to do is use the simulate function to simulate mouse down and it drags....
var stage = new Kinetic.Stage({
container: 'container',
width: 578,
height: 200
});
var layer = new Kinetic.Layer();
var rect = new Kinetic.Rect({
x: 20,
y: 20,
width: 100,
height: 50,
fill: 'green',
stroke: 'black',
strokeWidth: 4
});
//What I really want here is to start dragging the circle until the
//user releases the mouse, which would then place the circle.
rect.on('mousedown', function(evt) {
var userPos = stage.getUserPosition();
var latestElement = new Kinetic.Circle({
x: userPos.x,
y: userPos.y,
radius: 20,
fill: 'red',
stroke: 'black',
strokeWidth: 4,
draggable: true
})
layer.add(latestElement);
// Here's the bit you want. After adding the circle (with draggable:true) simulate the mousedown event on it which will initiate the drag
latestElement.simulate('mousedown');
layer.draw();
});
layer.add(rect);
stage.add(layer);​
http://jsfiddle.net/CPrEe/38/
http://kineticjs.com/docs/symbols/Kinetic.Node.php#simulate

Categories

Resources