Konva - visualize custom hit area - konvajs

Is there an easy way to visualize a custom hit area shape?
As described here
https://konvajs.github.io/docs/events/Custom_Hit_Region.html
the hitFunc attribute can be set to a function that uses the supplied context to draw a custom hit area / region. Something like this:
var star = new Konva.Star({
...
hitFunc: function (context) {
context.beginPath()
context.arc(0, 0, this.getOuterRadius() + 10, 0, Math.PI * 2, true)
context.closePath()
context.fillStrokeShape(this)
}
})
For debugging purposes, I would like an easy way to toggle visual rendering of the shape (circle in this case), eg by filling it yellow.
Thanks :)

Currently, there is no public API for that. But you still can add hit canvas into the page somewhere and see how it looks:
const hitCanvas = layer.hitCanvas._canvas;
document.body.appendChild(hitCanvas);
// disable absolute position:
hitCanvas.style.position = '';
http://jsbin.com/mofocagupi/1/edit?js,output
Or you can add hit canvas on top of the stage and apply an opacity to make scene canvases visible:
const hitCanvas = layer.hitCanvas._canvas;
stage.getContainer().appendChild(hitCanvas);
hitCanvas.style.opacity = 0.5;
hitCanvas.style.pointerEvents = 'none';
http://jsbin.com/gelayolila/1/edit?js,output

Related

How to get clicked element's position and id to change color and draw lines on it

I'm developing a basic window frame configurator. I splitted glasses in function below. I want to change color when i clicked and get the position of clicked glass to draw openin direction lines.
I tried to understand and implement Lavrton's method(https://codesandbox.io/s/0xj7zml2zl?file=/src/index.js) but i couldn't succeed.
function glassDraw(piece, frameWidth, frameHeight) {
var glassGroup = new Konva.Group();
for (i = 0; i <piece; i++) {
var glass = new Konva.Rect({
name: 'Rect',
x: padding + (frameWidth / piece) * i,
y: padding,
width: frameWidth / piece,
height: frameHeight - padding * 2,
fill: 'lightblue',
id: 'glass'+i,
});
glassGroup.add(glass);
}
glassGroup.find("Rect").on('click', function (e) {
// get id of the cube i drag
var clickedId = e.target.attrs.id;
$('#theId').html(clickedId);
})
return glassGroup;
}
When i use getelementbyid method with id of konva element("glass"+i), it returns null. I think i need to get as a konva element.
You have to create a click listener for all of your rectangles.
for (let rect of glassGroup.children) {
rect.on('click', () => {
console.log(rect.x(), rect.y()); // current position of the object
console.log(rect.id()); // log id of the object
rect.fill('green'); // set color to green
layer.batchDraw(); // update layer (batchDraw just for better performance .draw() would work to)
})
}
Make sure you always update the stage by either call stage.draw() or layer.draw() (or batchDraw() for better performance) after changing something, otherwise your stage will not show anything of what you do.
If something with this code don't work feel free to ask.
Have a nice day.

OpenLayers - lock rotation of box or rectangle geometry while modifying

Openlayers provides useful functions for drawing boxes and rectangles and also has ol.geom.Geometry.prototype.rotate(angle, anchor) for rotating a geometry around a certain anchor. Is it possible to lock the rotation of a box/rectangle while modifying it?
Using the OpenLayers example located here to draw a box with a certain rotation to illustrate the point:
I would like the box/rectangle to maintain its rotation while still being able to drag the sides longer and shorter. Is there a simple way to achieve this?
Answering with the solution I came up with.
First of all, add the feature(s) to a ModifyInteraction so you are able to modify by dragging the corners of the feature.
this.modifyInteraction = new Modify({
deleteCondition: eventsCondition.never,
features: this.drawInteraction.features,
insertVertexCondition: eventsCondition.never,
});
this.map.addInteraction(this.modifyInteraction);
Also, add event handlers upon the events "modifystart" and "modifyend".
this.modifyInteraction.on("modifystart", this.modifyStartFunction);
this.modifyInteraction.on("modifyend", this.modifyEndFunction);
The functions for "modifystart" and "modifyend" look like this.
private modifyStartFunction(event) {
const features = event.features;
const feature = features.getArray()[0];
this.featureAtModifyStart = feature.clone();
this.draggedCornerAtModifyStart = "";
feature.on("change", this.changeFeatureFunction);
}
private modifyEndFunction(event) {
const features = event.features;
const feature = features.getArray()[0];
feature.un("change", this.changeFeatureFunction);
// removing and adding feature to force reindexing
// of feature's snappable edges in OpenLayers
this.drawInteraction.features.clear();
this.drawInteraction.features.push(feature);
this.dispatchRettighetModifyEvent(feature);
}
The changeFeatureFunction is below. This function is called for every single change which is done to the geometry as long as the user is still modifying/dragging one of the corners. Inside this function, I made another function to adjust the modified rectangle into a rectangle again. This "Rectanglify"-function moves the corners which are adjacent to the corner which was just moved by the user.
private changeFeatureFunction(event) {
let feature = event.target;
let geometry = feature.getGeometry();
// Removing change event temporarily to avoid infinite recursion
feature.un("change", this.changeFeatureFunction);
this.rectanglifyModifiedGeometry(geometry);
// Reenabling change event
feature.on("change", this.changeFeatureFunction);
}
Without going into too much detail, the rectanglify-function needs to
find rotation of geometry in radians
inversely rotate with radians * -1 (e.g. geometry.rotate(radians * (-1), anchor) )
update neighboring corners of the dragged corner (easier to do when we have a rectangle which is parallel to the x and y axes)
rotate back with the rotation we found in 1
--
In order to get the rotation of the rectangle, we can do this:
export function getRadiansFromRectangle(feature: Feature): number {
const coords = getCoordinates(feature);
const point1 = coords[0];
const point2 = coords[1];
const deltaY = (point2[1] as number) - (point1[1] as number);
const deltaX = (point2[0] as number) - (point1[0] as number);
return Math.atan2(deltaY, deltaX);
}

openlayers-3 precompose, how to do layer clipping with a rectangular geometry

I'm trying to make a simple app doing something similar to the Layer Spy Example, but instead of a circle flowing the mouse pointer, I would like to do the clipping based on a rectangle which is always centered in the map.
(preferably with "fixed" size" i.e. changes "extent" when zooming)
Any help appreciated
Thanks
Frode
You can do it like in the example that you are referring to. But instead of context.arc() use context.rect() with a fixed position to clip the layer. Something like:
imagery.on('precompose', function(event) {
var ctx = event.context;
var pixelRatio = event.frameState.pixelRatio;
ctx.save();
ctx.beginPath();
var x = ctx.canvas.width / 2 - 100;
var y = ctx.canvas.height / 2 - 100;
ctx.rect(x, y, 100, 100);
ctx.clip();
});
http://jsfiddle.net/eo1c1x78/

How to interactively Draw a Circle in openlayers-3

I'am intersted in a fuctionality, that was present in openlayers-2, but absent at the moment in 3rd installment - interactive circle drawing.
As you can see in example here: http://openlayers.org/en/v3.0.0/examples/draw-and-modify-features.html
There's no available option for Circle. Even though comment states, that there should be available all of #type {ol.geom.GeometryType}, circle dowsen't work. Tried it myself with this piece of code:
function addInteraction(type) {
draw = new ol.interaction.Draw({
features: featureOverlay.getFeatures(),
type: /** #type {ol.geom.GeometryType} */ 'Circle'
});
map.addInteraction(draw);
}
Is there any native\patch\hack solutions present?
This feature has now been added in version 3.5.0, with an example here: http://openlayers.org/en/v3.5.0/examples/draw-features.html
It works exactly like you guessed, that is
draw = new ol.interaction.Draw({
features: featureOverlay.getFeatures(),
type: 'Circle'
});
map.addInteraction(draw);
I had nearly the same problem. The Question is if you want to add just a circle for styling reasons or you need it as a polygon? When you try too achieve a polygon you can easyily use the Poylgon.based circular function. As you can see in the source code below you only need the sphere. For example ol.sphere.WGS84. The center point and the radius. The optional input defines the number of points. which are used to define the circle.
ol.geom.Polygon.circular = function(sphere, center, radius, opt_n) {
var n = goog.isDef(opt_n) ? opt_n : 32;
/** #type {Array.<number>} */
var flatCoordinates = [];
var i;
for (i = 0; i < n; ++i) {
goog.array.extend(
flatCoordinates, sphere.offset(center, radius, 2 * Math.PI * i / n));
}
flatCoordinates.push(flatCoordinates[0], flatCoordinates[1]);
var polygon = new ol.geom.Polygon(null);
polygon.setFlatCoordinates(
ol.geom.GeometryLayout.XY, flatCoordinates, [flatCoordinates.length]);
return polygon;
};
It is even Api Stable so you can access it from outside. IN my case i created an own control which extended the draw feature. Hope i was able to help you.

Two ribbon with same z, they covered each other

I'm drawing map roads with THREE.Ribbon, every road has border with different color, so I use two ribbons, one is wider with the color of border, one is narrower, then I can achieve my purpose.
I also draw cap on two ends of ribbon with circles, certainly draw two circles, the smaller one covers bigger one, just like linecap in canvas2D.
I can't use THREE.Line as my alternative, because the maximum value of width of Line is 1 in my webgl.
My codes are just like this:
var circleShape = new THREE.Shape();
var circleRadius = lineWidth/2;
circleShape.moveTo( 0, circleRadius );
circleShape.quadraticCurveTo( circleRadius, circleRadius, circleRadius, 0 );
circleShape.quadraticCurveTo( circleRadius, -circleRadius, 0, -circleRadius );
circleShape.quadraticCurveTo( -circleRadius, -circleRadius, -circleRadius, 0 );
circleShape.quadraticCurveTo( -circleRadius, circleRadius, 0, circleRadius );
var circle = new THREE.ShapeGeometry( circleShape);
var material = new THREE.MeshBasicMaterial( { color: color, depthWrite: false} );
var mesh = new THREE.Mesh( circle, material );
this.parent.add( mesh );
var material = new THREE.MeshBasicMaterial( { color: widerColor, depthWrite: false} );
var widerRibbon = new THREE.Ribbon( widerGeometry, material );
this.parent.add( widerRibbon );
var material = new THREE.MeshBasicMaterial( { color: narrowerColor, depthWrite: false} );
var narrowerRibbon = new THREE.Ribbon( narrowerGeometry, material );
this.parent.add( narrowerRibbon );
My logic is the latter will cover the former. so narrower ribbon will cover wider ribbon, ribbon will cover half of circle.
My difficulty:
The consequence is they cover each other(without depthWrite:false).
I have found that THREE.MeshBasicMaterial can set depthWrite to false, I add it, then I find that narrower ribbon covered wider ribbon successfully, but what is weird is the cap on the ends of ribbon seems abnormal, when I look at the ribbon right on top, it works well, but when I look it with a angle, I find that the ribbon can't cover circle.
I don't know how to deal this issue, I just want the later drawing covers the former drawing when they all have same z coordinate.
Thanks for your guidance!
If you want to use "painter's algorith" (whatevr is painted last is always what you see), just turn Z off in the material(s). This is, set the "depthTest" attribute to false when declaring the material

Resources