Let's say I already have a bezier curve approximated by many straight lines (the bezier array in the code), and I would like to draw it with a series of rectangles. I have the following code below that does exactly this:
// don't change this array
const bezier = [{x:167.00,y:40.00},{x:154.37,y:42.09},{x:143.09,y:44.48},{x:133.08,y:47.15},{x:124.26,y:50.09},{x:116.55,y:53.27},{x:109.87,y:56.68},{x:104.15,y:60.31},{x:99.32,y:64.14},{x:95.28,y:68.15},{x:91.97,y:72.34},{x:89.31,y:76.67},{x:87.22,y:81.14},{x:85.63,y:85.74},{x:84.44,y:90.43},{x:83.60,y:95.22},{x:83.02,y:100.08},{x:82.63,y:105.00},{x:82.33,y:109.96},{x:82.07,y:114.94},{x:81.76,y:119.94},{x:81.33,y:124.93},{x:80.69,y:129.89},{x:79.77,y:134.82},{x:78.49,y:139.70},{x:76.78,y:144.50},{x:74.55,y:149.22},{x:71.74,y:153.84},{x:68.25,y:158.34},{x:64.03,y:162.71},{x:58.97,y:166.93},{x:53.02,y:170.98},{x:46.10,y:174.86},{x:38.11,y:178.54},{x:29.00,y:182.00}];
const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");
const thickness = 35;
function rotateCanvas(x, y, a) {
ctx.translate(x, y);
ctx.rotate(a);
ctx.translate(-x, -y);
}
function drawRectangle(rX, rY, rW, rH, rA, color) {
ctx.beginPath();
rotateCanvas(rX + rW / 2, rY + rH / 2, rA);
ctx.rect(rX, rY, rW, rH);
rotateCanvas(rX + rW / 2, rY + rH / 2, -rA);
ctx.fill();
}
function calcRectFromLine(x1, y1, x2, y2) {
const dx = x2 - x1;
const dy = y2 - y1;
const mag = Math.sqrt(dx * dx + dy * dy);
const angle = Math.atan2(dy, dx);
return {
x: (x1 + x2) / 2 - mag / 2,
y: (y1 + y2) / 2 - thickness / 2,
w: mag,
h: thickness,
a: angle
};
}
function calculateRectangles() {
const result = [];
for (let i = 1; i < bezier.length; i++) {
const prev = bezier[i - 1];
const curr = bezier[i];
result.push(calcRectFromLine(prev.x, prev.y, curr.x, curr.y));
}
return result;
}
const rectangles = calculateRectangles();
for (let r of rectangles) {
drawRectangle(r.x, r.y, r.w, r.h, r.a);
}
<canvas width="400" height="400"></canvas>
If you run the snippet you'll see that the curve is not fully thick, and the fact that it is a series of rectangles is very obvious.
If you change the thickness parameter from 35 to a lower number and re-run it, it looks fine. It's only when it's very thick does this occur.
The code currently takes the bezier array, and creates a series of rotated rectangles and then renders them.
Is there any way to modify the calculateRectangles function to return a better approximation of the curve? Ideally it would still return a list of rectangles rotated around their center, but when rendered it would look more like the curve, and less like a list of rectangles.
The only idea I could think of is to somehow return twice as many rectangles from calculateRectangles, where each one is inverted from the previous one, such that both sides of the line are filled in, and while I think that might work, it unfortunately has the side-effect of returning twice as many rectangles, which is undesirable and I would to avoid it if possible.
The shapes that you should draw are not rectangles but quadrilaterals, obtained by joining the endpoints of the successive normals to the curve. Presumably, you can achieve that by means of Path objects.
In zones of high curvature, you may have to yet reduce the step, because the outer curve might not be smooth.
In fact, you can "flatten" a Bezier curve by choosing steps so that the deviation between successive segments remains bounded below a fixed tolerance.
In the case of a thick curve, you can keep that idea but making sure that the bounded deviation holds for both sides of the curve.
you can't really make a "thick bezier" by drawing rectangles, you're just going to end up with lots of gaps between them on one size, and weird looking overlap on the other side. If you want to stick with the polygon approximation, you'll need to use the normal at each of your points, and then draw lines to connect those. This leads to trapezoidal sections, so we can't use plain rects if we want decent looking results.
However, the bigger the offset, the more you're going to have problems in areas with tiny radius of curvature: you can already see one such problem just by looking at the normals crossing each other underneath the crest in the upper left, where we don't actually want to connect all normal-offset vertices, because one of them lies inside the shape we want to trace.
Alternatively, you can offset the bezier curve itself with "more beziers", e.g. https://pomax.github.io/bezierinfo/#offsetting, but even then you're still going to have to resolve overlaps in the offset shape.
Instead, you can approximate the curve using circular arcs, which make "thickening the curve" a bit easier because you simply use the same arc angles and center, with two different values for the radius to get your two offset segments.
This is an okay first attempt, but I'm going to keep trying. Simply add this to the end of the getRectangles function add further approximation rectangles. Seems good enough for my purposes (and simple!), but I'm going to keep investigating a bit. I'm aware it doesn't work perfectly, but it's okay, and I don't really need much better than okay:
let len = result.length;
for (let i = 1; i < len; i++) {
const prevR = result[i - 1];
const currR = result[i - 0];
result.push({
x: (prevR.x + currR.x) / 2,
y: (prevR.y + currR.y) / 2,
w: (prevR.w + currR.w) / 2,
h: (prevR.h + currR.h) / 2,
a: (prevR.a + currR.a) / 2
});
}
Actually, this is slightly better than okay the more and more I play with it. I think this might be a good enough solution. Unless someone can come up with something better.
Here's a GIF of the difference:
I am trying to move an object smoothly from point A to point B using HTML canvas and regular javascript.
Point A is a set of coordinates
Point B is in the case the cursor location.
I made a jsfiddle of what I have so far: https://jsfiddle.net/as9fhmw8/
while(projectile.mouseX > projectile.x && projectile.mouseY < projectile.y)
{
ctx.save();
ctx.beginPath();
ctx.translate(projectile.x, projectile.y);
ctx.arc(0,0,5,0,2*Math.PI);
ctx.fillStyle = "blue";
ctx.fill();
ctx.stroke();
ctx.restore();
if(projectile.mouseX > projectile.x && projectile.mouseY < projectile.y)
{
var stepsize = (projectile.mouseX - projectile.x) / (projectile.y - projectile.mouseY);
projectile.x += (stepsize + 1);
}
if(projectile.mouseY < projectile.y)
{
var stepsize = (projectile.y - projectile.mouseY) / (projectile.mouseX - projectile.x);
projectile.y -= (stepsize + 1);
}
}
Essentially what I can't figure out to do is to make the while loop slower (so that it appears animated in stead of just going through every iteration and showing the result).
I also can't figure out how to prevent the Arc from duplicating so that it creates a line that is permanent, instead of appearing to move from point a to point b.
Smooth animation here is really about determining how far to move your object for each iteration of the loop.
There is a little math involved here, but it's not too bad.
Velocity
Velocity in your case is just the speed at which your particles travel in any given direction over a period of time. If you want your particle to travel 200px over the course of 4 seconds, then the velocity would be 50px / second.
With this information, you can easily determine how many pixels to move (animate) a particle given some arbitrary length of time.
pixels = pixelsPerSecond * seconds
This is great to know how many pixels to move, but doesn't translate into individual X and Y coordinates. That's where vectors come in.
Vectors
A vector in mathematics is a measurement of both direction and magnitude. For our purposes, it's like combining our velocity with an angle (47°).
One of the great properties of vectors is it can be broken down into it's individual X and Y components (for 2-Dimensional space).
So if we wanted to move our particle at 50px / second at a 47° angle, we could calculate a vector for that like so:
function Vector(magnitude, angle){
var angleRadians = (angle * Math.PI) / 180;
this.magnitudeX = magnitude * Math.cos(angleRadians);
this.magnitudeY = magnitude * Math.sin(angleRadians);
}
var moveVector = new Vector(50, 47);
The wonderful thing about this is that these values can simply be added to any set of X and Y coordinates to move them based on your velocity calculation.
Mouse Move Vector
Modeling your objects in this way has the added benefit of making things nice and mathematically consistent. The distance between your particle and the mouse is just another vector.
We can back calculate both the distance and angle using a little bit more math. Remember that guy Pythagoras? Turns out he was pretty smart.
function distanceAndAngleBetweenTwoPoints(x1, y1, x2, y2){
var x = x2 - x1,
y = y2 - y1;
return {
// x^2 + y^2 = r^2
distance: Math.sqrt(x * x + y * y),
// convert from radians to degrees
angle: Math.atan2(y, x) * 180 / Math.PI
}
}
var mouseCoords = getMouseCoords();
var data = distanceAndAngleBetweenTwoPoints(particle.x, particle.y, mouse.x, mouse.y);
//Spread movement out over three seconds
var velocity = data.distance / 3;
var toMouseVector = new Vector(velocity, data.angle);
Smoothly Animating
Animating your stuff around the screen in a way that isn't jerky means doing the following:
Run your animation loop as fast as possible
Determine how much time has passed since last time
Move each item based on elapsed time.
Re-paint the screen
For the animation loop, I would use the requestAnimationFrame API instead of setInterval as it will have better overall performance.
Clearing The Screen
Also when you re-paint the screen, just draw a big rectangle over the entire thing in whatever background color you want before re-drawing your items.
ctx.globalCompositeOperation = "source-over";
ctx.fillStyle = "black";
ctx.fillRect(0, 0, canvas.width, canvas.height);
Putting It All Together
Here is a Fiddle demonstrating all these techniques: https://jsfiddle.net/jwcarroll/2r69j1ok/3/
I want to make a Tetradecagon, a polygon with 14 sides, with Processing.JS.
(I want to make the Tetradecagon like the one shown in the Image below!)
Using the numbers given in the image, which I would like to replicate, I concluded that each piece (I don't know it's proper name), has an angle of 25.714285714°.....25 and 10/14 = 25 and 5/7 - 5/7 in decimal form = 0.714285714So, I arrived at 25.714285714°
Now, in Processing.JS, I was wanting to use a while loop:
var r = 0;
var draw = function() {
translate(200,200);
while(r < 361){
rotate(r);
r = r + 25.714285714;
line(200,0,200,200);
}
};
Here, I have set one variable, r. r will be the variable for the rotate() function. The while loop will keep going until r meets 360 - this will allow for the the change in r, the angle, to increase by 25.714285714°, while r < 361.
But, sadly, this is not happening. What I see on my canvas is the line being shot off the screen.
(edit) I added translate(200,200); just above the while() loop - this helped, but the lines are still not looking like the picture above.
The second point of the line is not staying in the center; the whole line is being shifted. I only want the first (top) point to be shifted by the given change in angles.
How do I change the code in order to achieve the goal that I am striving for? Any help would be appreciated - Thanks for your time!
P.S. This is my result with the current code -
Processing.js is just for running Processing code. This looks like a mix of Processing and Javascript code so my first advice would be "write real Processing code".
With that said, if you want to do this based on coordinate rotation, look at your 14-gon: it's 14 repeated triangles, so analyze one triangle and draw that 14 times. Any triangular slice is defined by a line from "the center" to "a vertex on the 14-gon" at a (necessary) distance r, the radius of the circumscribing circle. So, given a vertex (r,0) on the 14-gon where is the next vertex (nx,ny)?
Simple maths:
first vertex = (x, y) = (r,0)
next vertex = (nx,ny) = (r,0) rotated over (0,0) by (phi = tau/14)
(I'm using tau here because it's a far more convenient constant for programming purposes. It's simply equal to 2*pi, and as such represents an entire circle, rather than a half circle)
Now, computing that rotate coordinate using basic trigonometry:
nx = r * cos(phi) - 0 * sin(phi) = r * cos(phi)
ny = r * sin(phi) + 0 * cos(phi) = r * sin(phi)
Alright, done. And this nx,ny computation is clearly not specific to the number 14, it about arbitrary angles, so let's code the solution and make it work for any n-sided polygon:
void setup() {
size(400,400);
noLoop();
}
void draw() {
background(255);
// offset the coordinate system so that (0,0) is the sketch center
translate(width/2,height/2);
// then draw a polygon. In this case, radius width/2, and 14 sided
drawNgon(width/2, 14);
}
void drawNgon(float r, float n) {
// to draw (r,0)-(x',y') we need x' and y':
float phi = TAU/n;
float nx = r * cos(phi);
float ny = r * sin(phi);
// and then we just draw that line as many times as there are sides
for(int a=0; a<n; a++) {
// draw line...
line(r,0, nx,ny);
// rotate the entire coordinate system...
rotate(phi);
// repeat until done.
}
}
And now we can freely change both the polygon radius and the number of sides by changing the input to drawNgon(..., ...).
I am writing a simple game (in Javascript) where circular sprites can collide with each other. I store an angle (in degrees) and an x,y for each object. I have the collision detection working, but I need to work out which sprite hit the other. So for two objects colliding which one drove into the other (i.e. the front of which sprite made contact with the 'non front' of the other). Or to put it another way, which one rear ended the other. In the case of very close head on accidents e.g. where they make an absolute direct head on collision (180 degree collision) or are within say 5 degrees of doing so (175-185 degree collision), then I need to spot this and attribute no 'blame' to either sprite. What would the maths, or better still the code, for this be?
var angleA = Math.abs(collidedWith.angle - 180);
var angleB = Math.abs(this.angle - 180);
var angleConsideredHeadOn = 5;
var anglesSubtracted = Math.abs(angleA - angleB);
if (anglesSubtracted < angleConsideredHeadOn) {
var headOn = true;
}
if (anglesSubtracted >= angleConsideredHeadOn) {
// There was a non-head on crash
var xA = collidedWith.velocityX;
var yA = collidedWith.velocityY;
var xB = this.velocityX;
var yB = this.velocityY;
// Need to determine which sprites 'front' collided with the other's side or read
}
To detect the head-on case, take the dot product of their two (pre-impact) velocity vectors which will give you the cosine between their headings. If that value is less than -0.9 Pi then the collision is head on.
Otherwise, the sprite to blame is the one with the highest absolute velocity (since a slow sprite cannot possibly rear-end a fast sprite).
This seems to work...
// Javascript
// Two objects 'this' and 'collidedWith' have collided
// this code determines who head butted the other
// Based on having an angle and an X and Y velocity (xDir and yDir) where volicity could be negative (going left or up) or positive (going right or down)
// 'degrees' is a function which converts radians to degrees
var angleConsideredHeadOn = 15;
var theta_a = degrees(Math.atan2(this.xDir, this.yDir));
var theta_b = degrees(Math.atan2(collidedWith.xDir, collidedWith.yDir));
var a_to_b = degrees(Math.atan2(this.posY - collidedWith.posY, this.posX - collidedWith.posX)); // Normal angle from 'this's perspective
var b_to_a = -a_to_b % 360; // ditto from collidedWith's perspective
var collision_angle_a = Math.abs(theta_a - a_to_b) % 360
var collision_angle_b = Math.abs(theta_b - b_to_a) % 360
// Collision is close to head on
if (Math.abs(collision_angle_a - collision_angle_b) < angleConsideredHeadOn) return;
//
if (collision_angle_a < collision_angle_b) {
// 'collidedWith' head butted the other object
} else {
// 'this' head butted the other object
}
I am developing a casino based game using html5. The animation is working properly but this is not quite smooth i.e. once the wheel stops rotation I move ball as a final repositioning to smoothen the transition but it is not upto the expectation. Complete Code here
BallReposition Function - runs after I wheel stops movement for the final repositioning of the ball to give some reality to the animation.
function ballReposition(){
curX = findNearestOnCircle(curX);
if(curX > deadXRight){
sign = "-";
}else if(curX < deadXLeft){
sign = "+";
}
if(sign == "+"){
curX = parseInt(curX) + ballRepositionIncVal;
curY = Math.floor(Math.abs(getYOnCircle(curX, 130, 1)) + 0.5);
}else{
curX = parseInt(curX) - ballRepositionIncVal;
curY = Math.floor(Math.abs(getYOnCircle(curX, 130, 0)) + 0.5);
}
var xy = normalizeXY(curX, curY);
curX = parseInt(xy.split("-")[0]);
curY = parseInt(xy.split("-")[1]);
surface = document.getElementById("myCanvas");
var surfaceContext = surface.getContext("2d");
//removing older ball image.
surfaceContext.save();
// Translate to the center point of our image
surfaceContext.translate(happy.width * 0.5, happy.height * 0.5);
// Perform the rotation
surfaceContext.rotate(DegToRad(angle));
// Translate back to the top left of our image
surfaceContext.translate(-happy.width * 0.5, -happy.height * 0.5);
surface.getContext("2d").drawImage(happy, 0, 0);
surface.getContext("2d").drawImage(ball, curX, curY);
console.log(curX + curY);
surfaceContext.restore();
ballRepositionIncVal-=5;
if(ballRepositionIncVal <= 0){
clearInterval(myIntervalVar);
}
}
Other function details -
drawCanvas - loads the images and once the images are loaded it will start calling loop function which will rotate the wheel and move the ball in anticlockwise direction.
normalizeXY - used to put the ball at some discrete positions i.e. proper positions below numbers of wheel.
EDIT - Fiddle Configuration updated here
To create a realistic spinning wheel you can use a logarithmic-ish approach to reduce the speed of the wheel.
This means the angle is decremented by small per-centage for each frame. As it is per-centage you will get a smooth ending spin (you will also notice you get the infamous wagon wheel aliasing effect).
This online demo shows the loop isolated (implement as you please):
var angle = 2; /// start angle in radians
ctx.translate(w, h); /// prepare canvas for rotation (w and h = 50%)
ctx.globalAlpha = 0.67; /// optional bonus: motion blur(-ish)
loop(); /// start loop
function loop() {
ctx.rotate(a); /// use incremental rotation
ctx.drawImage(img, -w , -h);
/// spin down and only loop if angle > certain value
a *= 0.995;
/// continue if there is enough "inertia"
if (a > 0.001) requestAnimationFrame(loop);
}
The threshold value for continue the loop determines how "brutal" you want the stop to be. If you want the wheel to appear heavier (more mass) you can decrement the angle with an even tinier increment (eg. try 0.998).
For the ball to bounce around you need to resort to physics modelling, or at least pseudo-physics-modelling. This includes collision detections for all the small details on the wheel as well as sub-time-steps (ray casting) checking and positioning in z-axis.
I feel this is a bit broad to describe here on SO but find a good article on collision detection and physics simulation. Here is a good start with the basics.