fabricjs Polygon Redundant Area - fabricjs

2https://i.stack.imgur.com/2aZm2.png
1https://codepen.io/1gelistirici/pen/KKRjgoj[enter image description here]
// Initiate a Canvas instance
var canvas = new fabric.Canvas("canvas");
// Initiate a polygon instance
var polygon = new fabric.Polygon([
{ x: 200, y: 10 },
{ x: 250, y: 50 },
{ x: 250, y: 180},
{ x: 150, y: 180},
{ x: 150, y: 50 }], {
fill: 'green'
});
// Render the polygon in canvas
canvas.add(polygon);
Hi, I have created a polygon in fabricjs. Then I check your intersect. When the other object comes to a non-polygon but defined as a polygon by fabricjs, it is detected that it hits. How can I get ahead of this? Can you help me?

Check for intersection using object.containsPoint(). You can define the point as anywhere associated with the moving object coordinates.
var targetPoint = new fabric.Point(moveEventTarget.left, moveEventTarget.top);
// detect if move event target intersects with another object
if (intersectionObject.containsPoint(targetPoint)) {
if (!canvas.isTargetTransparent(intersectionObject, targetPoint.x, targetPoint.y)) {
// do something
};
};

Related

How can I save a Blend canvas?

I want to use the image and imageproc crates to draw triangles that blend if there are any overlapping triangles. Currently my code looks like this:
use image::{Rgba, RgbaImage};
use imageproc::drawing;
use imageproc::drawing::Blend;
use imageproc::point::Point;
struct Triangle([Point<i32>; 3]);
fn main() {
let triangle = Triangle([
Point { x: 0, y: 0 },
Point { x: 100, y: 400 },
Point { x: 400, y: 100 },
]);
let mut image = Blend(RgbaImage::new(400, 400));
drawing::draw_polygon_mut(&mut image, &triangle.0, Rgba([255, 255, 0, 255]));
drawing::draw_polygon_mut(&mut image, &triangle.0, Rgba([0, 0, 255, 255]));
image.save("test.png").unwrap();
}
This should produce a single white triangle, but there is no save method for Blend canvases. Is there an easy way to save this image?
The actual ImageBuffer object is inside of the Blend object.
You can extract it via either destructuring or .0.
Destructuring:
let Blend(image_buffer) = image;
image_buffer.save("test.png").unwrap();
.0:
image.0.save("test.png").unwrap();

PhaserJS: Issue with sprite animation

I have a small issue that and I’m not able to figure out what’s wrong, maybe someone can help.
It seems player.anims.play(‘walk’) is not working I get an error which reads “Cannot read property ‘frame’ of undefined”.
It seems I get an empty array of frames.
How I load my spreadsheet in preload():
this.load.spritesheet('player', 'assets/characters.png', { frameWidth: 32, frameHeight: 48 })
How my class looks :
export default class Player extends Phaser.Physics.Arcade.Sprite {
constructor(scene: Phaser.Scene, x: number, y: number) {
super(scene, x, y, 'player')
const player = scene.physics.add.sprite(x, y, 'player')
player.setCollideWorldBounds(true).setInteractive()
scene.anims.create({
key: 'walk',
frames: scene.anims.generateFrameNames('player', { start: 1, end: 3 }),
repeat: -1
})
player.anims.play('walk')
}
}
in create():
this.player = new Player(this, 10, 10)
Found the solution I’m using Phaser 3.21.0 and it seems that inside this.load.spritesheet I have to pass endFrame inside config object

Creating dynamic links on pointerdown event -JointJS

Is it possible to create interactive dynamic links in JointJS starting from a reference point (x,y) instead of drawing it from a port or using a halo.
Regards
Achyut
There are some undocumented methods in JointJS which might help you solve this. More inline.
paper.on('blank:pointerdown', function(evt, x, y) {
var linkView = this.getDefaultLink()
.set({
'source': { x: x, y: y },
'target': { x: x, y: y }
})
.addTo(this.model)
.findView(this);
// initiate the linkView arrowhead movement
linkView.startArrowheadMove('target');
$(document).on({
'mousemove.example': onDrag,
'mouseup.example': onDragEnd
}, {
// shared data between listeners
view: linkView,
paper: this
});
function onDrag(evt) {
// transform client to paper coordinates
var p = evt.data.paper.snapToGrid({
x: evt.clientX,
y: evt.clientY
});
// manually execute the linkView mousemove handler
evt.data.view.pointermove(evt, p.x, p.y);
}
function onDragEnd(evt) {
// manually execute the linkView mouseup handler
evt.data.view.pointerup(evt);
$(document).off('.example');
}
});

ThreeJS – smooth scaling object while mouseover

another ThreeJS question:
How can I make a hovered (intersected) object scale smooth to a defined size? My current code is
INTERSECTED.scale.x *= 1.5;
INTERSECTED.scale.y *= 1.5;
but this only works like on/off.
Edit: My Solution (with tweenJS)
While mouseOver I scale up the element to 200% :
function scaleUp(){
new TWEEN.Tween( INTERSECTED.scale ).to( {
x: 2,
y: 2
}, 350 ).easing( TWEEN.Easing.Bounce.EaseOut).start();
}
While mouseOut I scale down the element to 100% :
function scaleDown(){
new TWEEN.Tween( INTERSECTED.scale ).to( {
x: 1,
y: 1
}, 350 ).easing( TWEEN.Easing.Bounce.EaseOut).start();
}
Finally I call the functions in the mouse function.
if (intersects[0].object != INTERSECTED)
scaleUp();
else
scaleDown();
That's all. Very useful for UIs I think.
Using the tween library (found in three.js/examples/js/libs/tween.min.js) you can animate the scale like so:
function setupObjectScaleAnimation( object, source, target, duration, delay, easing )
{
var l_delay = ( delay !== undefined ) ? delay : 0;
var l_easing = ( easing !== undefined ) ? easing : TWEEN.Easing.Linear.None;
new TWEEN.Tween( source )
.to( target, duration )
.delay( l_delay )
.easing( l_easing )
.onUpdate( function() { object.scale.copy( source ); } )
.start();
}
and then call it like so:
setupObjectScaleAnimation( INTERSECTED,
{ x: 1, y: 1, z: 1 }, { x: 2, y: 2, z: 2 },
2000, 500, TWEEN.Easing.Linear.None );
Or if you want to use the render loop:
clock = new THREE.Clock();
time = clock.getElapsedTime();
INSPECTED.scale.x = time / 1000;
INSPECTED.scale.y = time / 1000;
You can change the divisor based on how fast or slow you want the animation to happen.

Drag and zoom text with Kineticjs

I am trying to zoom and pan a text which is draggable already. All the examples are on images or shapes and it seems I cannot adapt it to a text object. My questions are:
Do I have to use the anchors or is any simpler way zoom a text with Kineticjs?
I found an example regarding zooming a shape and the code crashes here:
var layer = new Kinetic.Layer({
drawFunc : drawTriangle //drawTriangle is a function defined already
});
Can we call a function while we are creating a layer?
I usually create a layer and then add the outcome of the function in it.
Any idea would be great, thanks.
I thought of many ways you could do this but this is the one I ended up implementing: jsfiddle
Basically, you have an anchor (which doesn't always have to be there, you can hide and show it if you would like. Let me know if you need help with that) and if you drag the anchor down it increases the fontSize, and if you drag the anchor up it decreases the fontSize.
I followed the exact same anchor tutorial but instead I added a dragBoundFunc to limit dragging to the Y-axis:
var anchor = new Kinetic.Circle({
x: x,
y: y,
stroke: '#666',
fill: '#ddd',
strokeWidth: 2,
radius: 8,
name: name,
draggable: true,
dragOnTop: false,
dragBoundFunc: function (pos) {
return {
x: this.getAbsolutePosition().x,
y: pos.y
};
}
});
And then I updated the updateAnchor() function to only detect the single anchor I added to the group named sizeAnchor:
var mY = 0;
function update(activeAnchor, event) {
var group = activeAnchor.getParent();
var sizeAnchor = group.get('.sizeAnchor')[0];
var text = group.get('.text')[0];
if (event.pageY < mY) {
text.setFontSize(text.getFontSize()-1);
} else {
text.setFontSize(text.getFontSize()+1);
}
sizeAnchor.setPosition(-10, 0);
mY = event.pageY;
}
Basically mY is used compared to the e.PageY to see if the mouse is moving up or down. Once we can determine the mouse direction, then we can decide if we should increase or decrease the fontSize!
Alternatively, you can use the mousewheel to do the exact same thing! I didn't implement it myself but it's definitely doable. Something like:
Mousewheel down and the fontSize decreases
Mousewheel up and the fontSize increases
Hopefully this emulates "Zooming" a text for you. And I guess being able to drag the text acts as "panning" right?
UPDATE (based on comment below)
This is how you would limit dragging to the Y-Axis using dragBoundFunc:
var textGroup = new Kinetic.Group({
x: 100,
y: 100,
draggable: true,
dragBoundFunc: function (pos) {
return {
x: this.getAbsolutePosition().x,
y: pos.y
};
}
});
See the updated jsfiddle (same jsfiddle as above)

Resources