Animate a circle being drawn using Paper.js - javascript

I'm trying to animate a circle being drawn using Paper.js.
As the circle tool is just a quick access for instantiating a path constructed via moveTo/arcTo etc, there are no arguments to support start and end angles (for open pie chart-like circles).
What I am looking for is a way to animate the circle being drawn from it's first point to an angle of my choice at a certain radius.
The actual canvas specification allows for explicit startAngle and endAngle to be specified. If this was the case within Paper.js I could easily achieve what I am looking for. However, within Paper.js I have yet to come across a method of replicating such control. I created something in Fabric.js that worked as Fabric's implementation of the circle shape used the same attributes as the arc command in the specification.
Does anyone know of a way this can be achieved so I can animate the endAngle?

Here's a conversion function that accepts html5 canvas arc arguments and returns the from, through, to arguments needed for a Paper.js arc.
function canvasArcToPaperArc(cx,cy,radius,startAngle,endAngle,strokecolor){
var startX=cx+radius*Math.cos(startAngle);
var startY=cy+radius*Math.sin(startAngle);
var endX=cx+radius*Math.cos(endAngle);
var endY=cy+radius*Math.sin(endAngle);
var thruX=cx+radius*Math.cos((endAngle-startAngle)/2);
var thruY=cy+radius*Math.sin((endAngle-startAngle)/2);
var from = new Point(startX,startY);
var through = new Point(thruX,thruY);
var to = new Point(endX,endY);
return({from:from, through:through, to:to});
}

Related

Is There Any Function or Algorithm For [Draw a Feature Surrounds Another Feature]?

I have to use OpenLayers to create a logic that draws two Features.
After the user draws Feature A,
We need logic to draw Feature B that surrounds the Feature A outside.
Draw Feature A on a map.
After Feature A is drawn, the system must create Feature B that surrounds Feature A.
The final result should be the same as Image.
PRECONDITION
Feature can have 3 - 6 angles.
The length of each side is unpredictable.
The angle of each side is unpredictable.
All sides of Feature B must be made from all sides of Feature A with the distance specified by the user.
How do we solve this problem?
full source code : https://github.com/JeahaOh/OpenLayersStudy/tree/master/Examples/EffectiveRange/CDN
Hey this looks like creating a geometry with a buffer of x (x is defined by the user).
You can use JSTS to create buffers from a geometry and then map it back to an openlayer geometry.
OpenLayers example that draws geometries with a buffer. This example uses LineString geometries but you can use any geometry.
Looking at your example you probably want sharp edges on your outer geometry so you can use a mitre line join style
var bufParams = new jsts.operation.buffer.BufferParameters();
bufParams.setJoinStyle(
jsts.operation.buffer.BufferParameters.JOIN_MITRE)
var outer = inner.buffer(spacing, bufParams);
See docs for BufferParameters for more options.
Here is a jsfiddle that shows it.

p5.js - collision detection while using translate

I'm having a problem I can't seem to solve when using the p5 javascript library. Essentially I want to create a random "snake" of circles in p5.js.
My code looks like this.
function setup() {
createCanvas(400, 400)
background(220)
noFill()
noLoop()
}
function draw() {
translate(200,200)
strokeWeight(1)
for(j=0;j<5;j++) {
snake()
}
}
function snake() {
rad = 10
ellipse(0,0,rad,rad)
push()
for(i=0;i<100;i++) {
a = random(0,360)
translate(rad*sin(a),rad*cos(a))
ellipse(0,0,rad,rad)
}
pop()
}
What I do is create a circle in the centre, then select a random point 360 degrees around that circle at a certain radius from it, and create a new circle there. Then I translate the centre point (the 0,0) to the centre of that new circle and start the process again.
That delivers a snake, but the problem is the circles inevitably start overlapping.
What I want to do is have my code check whether a randomly created new circle will overlap with any of the previous ones, and if it does, select a new location for that circle.
All the approaches to overlap detection in p5.js I encountered so far, however, use distance to calculate whether circles overlap. Which of course the use of translate messes up.
So if anyone has a solution for my problem, feel free to let me know.
You need to store the positions and sizes of the circles in some kind of data structure, like an array. Then check against those circles before you create a new one.
You might be able to do this using the translate() function, but if I were you I would instead do the translation myself. Instead of using the translate() function, keep track of the circle X and circle Y, and move that point as you draw new circles.
This will allow you to work in screen coordinates, which will make it easier to do collision detection.

XTK - Toolkit.. the cube moves by should only rotating

Im a newbie in 3D computer graphics and seen an odd thing.
I used the XTK-Toolkit, witch is great with DICOM. I add a cube in the scene and translated it far from the center (http://jsfiddle.net/64L47wtd/2/).
when the cube rotate it looks like it is moving
Is this a bug in XTK, or an principle problem with 3D rendering?
window.onload = function() {
// create and initialize a 3D renderer
var r = new X.renderer3D();
r.init();
// create a cube
cube = new X.cube();
// skin it..
cube.texture.file = 'http://x.babymri.org/?xtk.png';
cube.transform.translateX(250);
cube.transform.translateY(200);
cube.transform.translateX(270);
r.add(cube); // add the cube to the renderer
r.render(); // ..and render it
// add some animation
r.onRender = function() {
// rotation by 1 degree in X and Y directions
cube.transform.rotateX(1);
cube.transform.rotateY(1);
};
};
You miss to consider the cube a compound object consisting of several vertices, edges and/or faces. As a compound object it's using local coordinate system consisting of axes X, Y, Z. The actual cube is described internally using coordinates for vertices related to that cube-local coordinate system.
By "translating" you declare those relative coordinates of vertices being adjusted prior to applying inside that local coordinate system. Rotation is then still working on the axes of that local coordinate system.
Thus, this isn't an error of X toolkit.
You might need to put the cube into another (probably fully transparent) container object to translate/move it, but keep rotating the cube itself.
I tried to extend your fiddle accordingly but didn't succeed at all. Taking obvious intentions of X Toolkit into account this might be an intended limitation of that toolkit for it doesn't obviously support programmatic construction of complex scenes consisting of multi-level object hierarchies by relying on its API only.

html5 canvas - Saving paths or clip areas to reuse

I'm currently implementing a 2d deformable terrain effect in a game I'm working on and its going alright but I can envision it becoming a performance hog very fast as I start to add more layers to the effect.
Now what I'm looking for is a way to possibly save a path, or clipping mask or similar instead of having to store each point of the path in the terrain that i need to draw through each frame. And as I add more layers I will have to iterate over the path more and more which could contain thousands of points.
Some very simple code to demonstrate what I'm currently doing
for (var i = 0; i < aMousePoints.length; i++)
{
cRenderContext.save();
cRenderContext.beginPath();
var cMousePoint = aMousePoints[i];
cRenderContext.arc(cMousePoint.x, cMousePoint.y, 30, 0, 2 * Math.PI, false);
cRenderContext.clip();
cRenderContext.drawImage(cImg, 0, 0);
cRenderContext.closePath();
cRenderContext.restore();
}
Basically I'm after an effecient way to draw my clipping mask for my image over and over each frame
Notice how your clipping region stays exactly the same except for its x/y location. This is a big plus.
The clipping region is one of the things that is saved and restored with context.save() and context.restore() so it is possible to save it that way (in other words defining it only once). When you want to place it, you will use ctx.translate() instead of arc's x,y.
But it is probably more efficient to do it a second way:
Have an in-memory canvas (never added to the DOM or shown on the page) that is solely for containing the clipping region and is the size of the clipping region
Apply the clipping region to this in-memory canvas, and then draw the image onto this canvas.
Then use drawImage with the in-memory canvas onto your game context. In other words: cRenderContext.drawImage(in-memory-canvas, x, y); where x and y are the appropriate location.
So this way the clipping region always stays in the same place and is only ever drawn once. The image is moved on the clipping-canvas and then drawn to look correct, and then the in-memory canvas is drawn to your main canvas. It should be much faster that way, as calls to drawImage are far faster than creating and drawing paths.
As a separate performance consideration, don't call save and restore unless you have to. They do take time and they are unnecessary in your loop above.
If your code is open-source, let me know and I'll take a look at it performance-wise in general if you want.
Why not have one canvas for the foreground and one canvas for the background? Like the following demo
Foreground/Background Demo (I may of went a little overboard making the demo :? I love messing with JS/canvas.
But basically the foreground canvas is transparent besides the content, so it acts like a mask over the background canvas.
It looks like it is now possible with a new path2D object.
The new Path2D API (available from Firefox 31+) lets you store paths, which simplifies your canvas drawing code and makes it run faster. The constructor provides three ways to create a Path2D object:
new Path2D(); // empty path object
new Path2D(path); // copy from another path
new Path2D(d); // path from from SVG path data
The third version, which takes SVG path data to construct, is especially handy. You can now re-use your SVG paths to draw the same shapes directly on a canvas as well:
var p = new Path2D("M10 10 h 80 v 80 h -80 Z");
Information is taken from Mozilla official site.

Mask for putImageData with HTML5 canvas?

I want to take an irregularly shaped section from an existing image and render it as a new image in Javascript using HTML5 canvases. So, only the data inside the polygon boundary will be copied. The approach I came up with involved:
Draw the polygon in a new canvas.
Create a mask using clip
Copy the data from the original canvas using getImageData (a rectangle)
Apply the data to the new canvas using putImageData
It didn't work, the entire rectangle (e.g. the stuff from the source outside the boundary) is still appearing. This question explains why:
"The spec says that putImageData will not be affected by clipping regions." Dang!
I also tried drawing the shape, setting context.globalCompositeOperation = "source-in", and then using putImageData. Same result: no mask applied. I suspect for a similar reason.
Any suggestions on how to accomplish this goal? Here's basic code for my work in progress, in case it's not clear what I'm trying to do. (Don't try too hard to debug this, it's cleaned up/extracted from code that uses a lot of functions that aren't here, just trying to show the logic).
// coords is the polygon data for the area I want
context = $('canvas')[0].getContext("2d");
context.save();
context.beginPath();
context.moveTo(coords[0], coords[1]);
for (i = 2; i < coords.length; i += 2) {
context.lineTo(coords[i], coords[i + 1]);
}
//context.closePath();
context.clip();
$img = $('#main_image');
copy_canvas = new_canvas($img); // just creates a new canvas matching dimensions of image
copy_ctx = copy.getContext("2d");
tempImage = new Image();
tempImage.src = $img.attr("src");
copy_ctx.drawImage(tempImage,0,0,tempImage.width,tempImage.height);
// returns array x,y,x,y with t/l and b/r corners for a polygon
corners = get_corners(coords)
var data = copy_ctx.getImageData(corners[0],corners[1],corners[2],corners[3]);
//context.globalCompositeOperation = "source-in";
context.putImageData(data,0,0);
context.restore();
dont use putImageData,
just make an extra in memory canvas with document.createElement to create the mask and apply that with a drawImage() and the globalCompositeOperation function (depending on the order you need to pick the right mode;
I do something similar here the code is here (mind the CasparKleijne.Canvas.GFX.Composite function)

Categories

Resources