trying to recreate the battle-royale red-zone feature using some trig and the JavaScript canvas - javascript

The Problem:
If you've ever played or watched some gameplay of a battle royal game (like PUBG, for example), you'll always find an event during any battle called the red zone.
Basically, at a certain point in time during the game, a random zone on the map (possibly a square, possibly a circle) will be bombarded with artillery fire, for around 30 seconds or so. The game will fire, say, 20 shells at random positions within that red zone. If you're in the red zone, and it happens that you are within the splash radius (see below) of the shell, you will instantly die.
My attempt at recreating the Red-Zone feature using the JS canvas:
using an eventListener, whenever the user clicks on the canvas, a random point will be generated and a circle of radius 50 will be plotted around that point, but there's a catch:
If the point generated is less than 50 units away from the border of the zone or the point generated is less than 100 units away from another already generated point, the algorithm will keep generating new points and test it against the 2 previously stated conditions until it meets them, then it will add that point to the array containing all the dots.
The algorithm does work as intended for all test cases, but sometimes the first point, and ONLY the first point generated, violates these 2 conditions. I have no idea why. I've tried using a do-while loop instead of a while loop, (which keeps generating new points until one meets the 2 conditions), but no luck.
Please help me with this issue as fast as possible. Thanks in advance. Here's the code (CodePen): https://codepen.io/Undefined_Variable/full/oQeoqE/
let canvas = document.body.querySelector("canvas");
let ctx = canvas.getContext("2d");
canvas.width = 0.75 * screen.width;
canvas.height = 0.8 * screen.height;
let CW = canvas.width;
let CH = canvas.height;
canvas.style.top = (screen.height / 2) - (canvas.height / 2) + "px";
canvas.style.left = (screen.width / 2) - (canvas.width / 2) + "px";
let dotArr = [];
let dotSize = 50
let dotDistance = 100;
let borderDistance = 50;
let dotCounter = 0;
class dot {
constructor(posX, posY) {
this.posX = posX;
this.posY = posY;
this.radius = dotSize;
}
drawDot() {
ctx.save();
ctx.translate(this.posX, this.posY);
ctx.fillStyle = "black";
ctx.beginPath();
ctx.arc(0, 0, this.radius, 0, Math.PI * 2);
ctx.closePath();
ctx.fill();
ctx.restore();
}
}
function mainLoop() {
function drawCircle() {
ctx.save();
ctx.translate(CW / 2, CH / 2);
ctx.strokeStyle = "black";
ctx.beginPath();
ctx.arc(0, 0, 0.25 * CW, 0, Math.PI * 2);
ctx.closePath();
ctx.stroke();
ctx.restore();
}
function drawDots() {
for (let dot of dotArr) {
dot.drawDot();
}
}
ctx.clearRect(0, 0, CW, CH);
drawCircle();
drawDots();
requestAnimationFrame(mainLoop);
}
function addDot() {
function generateDot() {
let center_x = CW / 2;
let center_y = CH / 2;
let angle = Math.random() * 360;
let distance = Math.random() * (0.25 * CW);
let radius = 0.25 * CW;
return [center_x + Math.cos(angle) * distance, center_y + Math.sin(angle) * distance, center_x + Math.cos(angle) * radius, center_y + Math.sin(angle) * radius]
}
function verifyDotPosition(xPar, yPar, xBorder, yBorder) {
for (let dot of dotArr) {
if (Math.sqrt(Math.pow(xPar - dot.posX, 2) + Math.pow(yPar - dot.posY, 2)) < dotDistance) {
return false;
}
if (Math.sqrt(Math.pow(xPar - xBorder, 2) + Math.pow(yPar - yBorder, 2)) < borderDistance) {
return false;
}
}
dotCounter++;
return true;
}
let newDots = generateDot();
let x1 = newDots[0];
let y1 = newDots[1];
let x2 = newDots[2];
let y2 = newDots[3];
while (!verifyDotPosition(x1, y1, x2, y2)) {
newDots = generateDot();
x1 = newDots[0];
y1 = newDots[1];
x2 = newDots[2];
y2 = newDots[3];
}
if (dotCounter < 10) {
dotArr.push(new dot(x1, y1));
} else {
canvas.removeEventListener("click", addDot);
}
}
mainLoop();
canvas.addEventListener("click", addDot);
canvas {
border: 1px solid black;
position: absolute;
}
body {
margin: 0;
}
<!DOCTYPE html>
<html>
<head>
<title>redZone-demo</title>
</head>
<body>
<canvas></canvas>
</body>
</html>
-each shell has a splash radius, if you are inside a circle of a radius equal to that splash radius surrounding the point where the shell hit it, you will die
Clarification:
When I said that sometimes the algorithm doesn't work for the first point, I mean that sometimes the first point is generated too close to the border of the "red zone".

Related

js canvas simulate infinite, pan- and zoomable grid

So I have created an html canvas with the illusion of an infinite grid. My goal was to make it as efficient as possible, drawing only what is visible and simulating all the effects by doing the math, instead of for example drawing the grid 3-times as wide and high to make it "infinite". I implemented it by storing the x- and y-offset of the grid. When the mouse moves, the offset is being increased by the moved distance, and then clamped to the cell size. This way, when the moved distance is bigger than the size of one cell, the offset starts again at 0, because only the "overlapping distance" needs to be drawn. This way I can create the illusion of an infinite grid without actually having to worry about world coordinates etc. The snippet below is a working version of this:
let canvas = document.querySelector("canvas");
let ctx = canvas.getContext("2d");
let width = 200;
let height = 200;
let dpi = 4;
let cellSize = 10;
let pressed = false;
canvas.height = height * dpi;
canvas.width = width * dpi;
canvas.style.height = height + "px";
canvas.style.width = width + "px";
canvas.addEventListener("mousedown", (e) => mousedown(e));
canvas.addEventListener("mouseup", (e) => mouseup(e));
canvas.addEventListener("mousemove", (e) => mousemove(e));
let offset = {x: 0, y: 0};
draw();
function draw() {
ctx.save();
ctx.scale(dpi, dpi);
ctx.translate(-0.5, -0.5);
ctx.lineWidth = 1;
ctx.strokeStyle = "silver";
ctx.beginPath();
for (let x = offset.x; x < width; x += cellSize) {
ctx.moveTo(x, 0);
ctx.lineTo(x, height);
}
for (let y = offset.y; y < height; y += cellSize) {
ctx.moveTo(0, y);
ctx.lineTo(width, y);
}
ctx.closePath();
ctx.stroke();
ctx.restore();
}
function mousedown(e) {
pressed = true;
}
function mouseup(e) {
pressed = false;
}
function mousemove(e) {
if (!pressed) {
return;
}
ctx.clearRect(0, 0, width * dpi, height * dpi);
offset.x += e.movementX;
offset.y += e.movementY;
let signX = offset.x > 0 ? 1 : -1;
let signY = offset.y > 0 ? 1 : -1;
offset = {
x: (Math.abs(offset.x) > cellSize)
? offset.x - Math.floor((offset.x * signX) / cellSize) * cellSize * signX
: offset.x,
y: (Math.abs(offset.y) > cellSize)
? offset.y - Math.floor((offset.y * signY) / cellSize) * cellSize * signY
: offset.y
};
draw();
}
canvas {
background-color: white;
}
<canvas></canvas>
I now wanted to implement zooming into the illusion. This could be achieved by increasing the cell size according to the zoom level. I also changed the way the grid was drawn: Instead of clamping the offset, and beginning to draw the lines at that offset, the offset is now the center of the grid (thats why its starting position is at w/2 and h/2). I then draw the lines from the offset to the left, top, bottom and right edge. This allows me, when zooming, to simply set the offset to the mouse position, and increase the cell size. This way it looks like it would zoom to the mouse position, because the cell size increases "away" from that point. This works fine and looks pretty nice so far, try it out below:
let canvas = document.querySelector("canvas");
let ctx = canvas.getContext("2d");
let width = 200;
let height = 200;
let dpi = 4;
let cellSize = 10;
let pressed = false;
let zoomIntensity = 0.1;
let zoom = 1;
canvas.height = height * dpi;
canvas.width = width * dpi;
canvas.style.height = height + "px";
canvas.style.width = width + "px";
canvas.addEventListener("mousedown", (e) => mousedown(e));
canvas.addEventListener("mouseup", (e) => mouseup(e));
canvas.addEventListener("mousemove", (e) => mousemove(e));
canvas.addEventListener("wheel", (e) => wheel(e));
let offset = {x: width / 2, y: height / 2};
draw();
function draw() {
ctx.save();
ctx.scale(dpi, dpi);
ctx.translate(-0.5, -0.5);
ctx.lineWidth = 1;
ctx.strokeStyle = "silver";
ctx.beginPath();
for (let x = offset.x; x < width; x += cellSize * zoom) {
ctx.moveTo(x, 0);
ctx.lineTo(x, height);
}
for (let x = offset.x; x > 0; x -= cellSize * zoom) {
ctx.moveTo(x, 0);
ctx.lineTo(x, height);
}
for (let y = offset.y; y < height; y += cellSize * zoom) {
ctx.moveTo(0, y);
ctx.lineTo(width, y);
}
for (let y = offset.y; y > 0; y -= cellSize * zoom) {
ctx.moveTo(0, y);
ctx.lineTo(width, y);
}
ctx.closePath();
ctx.stroke();
ctx.fillStyle = "red";
ctx.arc(offset.x, offset.y, 4, 0, 2*Math.PI);
ctx.fill();
ctx.restore();
}
function mousedown(e) {
pressed = true;
}
function mouseup(e) {
pressed = false;
}
function mousemove(e) {
if (!pressed) {
return;
}
offset.x += e.movementX;
offset.y += e.movementY;
let signX = offset.x > 0 ? 1 : -1;
let signY = offset.y > 0 ? 1 : -1;
/*offset = {
x: (Math.abs(offset.x) > cellSize)
? offset.x - Math.floor((offset.x * signX) / cellSize) * cellSize * signX
: offset.x,
y: (Math.abs(offset.y) > cellSize)
? offset.y - Math.floor((offset.y * signY) / cellSize) * cellSize * signY
: offset.y
};*/
update();
}
function update() {
ctx.clearRect(0, 0, width * dpi, height * dpi);
draw();
}
function wheel(e) {
offset = {x: e.offsetX, y: e.offsetY};
zoom += ((e.deltaY > 0) ? -1 : 1) * zoomIntensity;
update();
}
canvas {
background-color: white;
}
<p>Scroll with mouse wheel<p>
<canvas></canvas>
However, as you might have noticed, when changing the mouse position while zooming, the grid looks like it jumps to that position. That is logical, because the new center of the grid is exactly at the mouse position - regardless of the distance of the mouse to the nearest cell. This way, when trying to zoom in on the center of a cell, the new grid creates a line exactly at that center, making it look like it jumped. I tried to store the offset of the mouse position to the nearest cell border and drawing everything shifted by that offset, but I couldnt get it to work. I would need to know when a new wheel event is initiated (like on mousedown) and then store the offset to the nearest cells borders, and draw everything shifted by those offsets * zoom, until the zooming ended. I am having trouble implementing something like that, because there are no inbuilt listener functions for the wheel besides wheel, and using something different like keyboard etc. isnt an option here. It is still my goal to make that illusion as efficient as it can be, trying to avoid ctx.scale() and ctx.translate and rather calculate the coords myself.
I was able to solve it on my own after many hours of trying different mathematical approches. At the end of this answer you will find a working snippet that simulates an infinite, pan- and zoomable grid. Because Im doing all the maths myself and draw only whats visible, the illusion of the infinite grid is really fast and efficient. You might notice that the lines are sometimes blurry when zooming in, this could be solved by rounding the numbers at which the lines are drawn to integers, however then you will notice small "jumps" while zooming in, because the lines are slighty shifted. I will now give my best to try to explain process how I achieved the illusion and explain the mathematical procedures.
Quick notes for the snippet:
zoomPoint (red point) is the point around the grid should be zoomed
rx and ry (blue lines) are the offset from the zoomPoint to the right or bottom border of the nearest cell
the top, left, bottom and right variables are the coordinates, at which the borders of the cell around the zoomPoint should be drawn
How does the zooming work?
on zoom, store the current zoomPoint in lastZoomPoint
update zoomPoint to new position of mouse
store current scale in lastScale
update scale by adding scaleStep * amt where amt is -1 or 1, depending on the wheels scrolling direction (deltaY)
calculate rx and ry (the distances from the new zoomPoint to the nearest vertical or horizontal line). it is important to use lastZoomPoint and lastScale here! Here is a piece of my notes to better understand exactly whats going on(needed for the following explanation):
picture
multiply rx and ry with scale, and draw the new grid
So we want to calculate the new rx (and ry, but once we have a formula for rx we can use that to calculate ry).
P2 (the green point) is our lastZoomPoint. We need the new rx, in the picture its called rneu. To get that, we want to subtract the yellow distance from Pneu. But actually, we can make this simpler. We only need a point that we know is perfectly on any of the vertical lines, lets call it Pv. Because rneu is the distance of Pneu to the next vertical line on its left, we need a point Pnearest, exactly on that vertical line. We can get that Point by just moving Pv by the size of one cell times the amount of cells between the two points. Well, we know the size of one cell (cellSize * lastScale), we now need the number of cells in between Pv and Pnearest. We can get that number by calculating the x-distance of these two points and divide it by the size of one cell. Lets use Math.floor to get the number of whole cells in between. Multiply that number by the size of one cell and add it to Pv and voilĂ , we get Pnearest. Lets write that down mathematically:
let Rneu = Pneu - Pnearest
let Pnearest = Pv + NWholeCells * scaledCellSize
let NWholeCells = Math.floor((Pneu - Pv) / (scaledCellSize))
let scaledCellSize = lastScale * cellSize
Substitute everything in, we get:
let Rneu = Pneu - (Pv + Math.floor((Pneu - Pv) / (lastScale * cellSize)) * (lastScale * cellSize))
So we know Pneu, lastScale and cellSize. The only thing missing is Pv. Remember, this was any Point that lies perfectly on one of the vertical lines. And this is going to be straightforward: Subtract rx (the one from the previous calculation) from P2 and we have ourselves a point that is perfectly on a vertical line!
So:
let Pv = P2 - rx
// substitue that in again
let Rneu = Pneu - ((P2 - rx) + Math.floor((Pneu - (P2 - rx)) / (lastScale * cellSize)) * (lastScale * cellSize));
Nice! Simplify that, and we get:
let Rneu = Pneu - P2 + rx - Math.floor((Pneu - P2 + rx) / (lastScale * cellSize)) * lastScale * cellSize);
In the snippet Pneu - P2 + rx is called dx.
So, now we have the distance from our new zoomPoint to the nearest vertical line. This distance however is obviously scaled by lastScale, so we need to divide rx by lastScale (this will become cleared in further explanation)
Now we have a "cleansed" rx. This "cleansed" value is the distance Pneu to the nearest cell border, if the scale was equal to 1. This is our "initial state". From that (this is now in calculateDrawingPositions()), to make it appear as if we were zooming in on Pneu, we only need to multiple the "cleansed" rx by the new scale (this time not lastScale but scale!). Now we start drawing the vertical lines of our new grid at Pneu - rx * scale, and decrease that x by cellSize * scale, until x reached 0. We now have the vertical lines on the left of our Pneu. Do the same for the horizontal lines above Pneu, and the starting points for the lines on the right or below are easily calculated by adding cellSize * scale to the left or top drawing position.
Puh, done! Thats it! I hope I didnt miss something in my explanation and everything is correct. It took me long to come up with that solution, I hope I explained it in a way it can be easily understood, however I dont know if thats even possible, for me this whole task was pretty complex.
let canvas = document.querySelector("canvas");
let ctx = canvas.getContext("2d");
let width = 200;
let height = 200;
let dpi = 4;
let cellSize = 10;
let backgroundColor = "white";
let lineColor = "silver";
let pressed = false;
let scaleStep = 0.1;
let scale = 1;
let lastScale = scale;
let maxScale = 10;
let minScale = 0.1;
let zoomPoint = {
x: 0,
y: 0
};
let lastZoomPoint = zoomPoint;
let rx = 0,
ry = 0;
let left = 0,
right = 0,
_top = 0,
bottom = 0;
resizeCanvas();
addEventListeners();
calculate();
draw();
function resizeCanvas() {
canvas.height = height * dpi;
canvas.width = width * dpi;
canvas.style.height = height + "px";
canvas.style.width = width + "px";
}
function addEventListeners() {
canvas.addEventListener("mousedown", (e) => mousedown(e));
canvas.addEventListener("mouseup", (e) => mouseup(e));
canvas.addEventListener("mousemove", (e) => mousemove(e));
canvas.addEventListener("wheel", (e) => wheel(e));
}
function calculate() {
calculateDistancesToCellBorders();
calculateDrawingPositions();
}
function calculateDistancesToCellBorders() {
let dx = zoomPoint.x - lastZoomPoint.x + rx * lastScale;
rx = dx - Math.floor(dx / (lastScale * cellSize)) * lastScale * cellSize;
rx /= lastScale;
let dy = zoomPoint.y - lastZoomPoint.y + ry * lastScale;
ry = dy - Math.floor(dy / (lastScale * cellSize)) * lastScale * cellSize;
ry /= lastScale;
}
function calculateDrawingPositions() {
let scaledCellSize = cellSize * scale;
left = zoomPoint.x - rx * scale;
right = left + scaledCellSize;
_top = zoomPoint.y - ry * scale;
bottom = _top + scaledCellSize;
}
function draw() {
ctx.save();
ctx.scale(dpi, dpi);
ctx.fillStyle = backgroundColor;
ctx.fillRect(0, 0, width, height);
ctx.lineWidth = 1;
ctx.strokeStyle = lineColor;
ctx.translate(-0.5, -0.5);
ctx.beginPath();
let scaledCellSize = cellSize * scale;
for (let x = left; x > 0; x -= scaledCellSize) {
ctx.moveTo(x, 0);
ctx.lineTo(x, height);
}
for (let x = right; x < width; x += scaledCellSize) {
ctx.moveTo(x, 0);
ctx.lineTo(x, height);
}
for (let y = _top; y > 0; y -= scaledCellSize) {
ctx.moveTo(0, y);
ctx.lineTo(width, y);
}
for (let y = bottom; y < height; y += scaledCellSize) {
ctx.moveTo(0, y);
ctx.lineTo(width, y);
}
ctx.stroke();
/* Only for understanding */
ctx.strokeStyle = "blue";
ctx.beginPath();
ctx.moveTo(zoomPoint.x, zoomPoint.y);
ctx.lineTo(left, zoomPoint.y);
ctx.moveTo(zoomPoint.x, zoomPoint.y);
ctx.lineTo(zoomPoint.x, _top);
ctx.stroke();
ctx.fillStyle = "red";
ctx.beginPath();
ctx.arc(zoomPoint.x, zoomPoint.y, 2, 0, 2*Math.PI);
ctx.fill();
/* -----------------------*/
ctx.restore();
}
function update() {
ctx.clearRect(0, 0, width * dpi, height * dpi);
draw();
}
function move(dx, dy) {
zoomPoint.x += dx;
zoomPoint.y += dy;
}
function zoom(amt, point) {
lastScale = scale;
scale += amt * scaleStep;
if (scale < minScale) {
scale = minScale;
}
if (scale > maxScale) {
scale = maxScale;
}
lastZoomPoint = zoomPoint;
zoomPoint = point;
}
function wheel(e) {
zoom(e.deltaY > 0 ? -1 : 1, {
x: e.offsetX,
y: e.offsetY
});
calculate();
update();
}
function mousedown(e) {
pressed = true;
}
function mouseup(e) {
pressed = false;
}
function mousemove(e) {
if (!pressed) {
return;
}
move(e.movementX, e.movementY);
// do not recalculate the distances again, this wil lead to wronrg drawing
calculateDrawingPositions();
update();
}
canvas {
border: 1px solid black;
}
<p>Zoom with wheel, move by dragging</p>
<canvas></canvas>

Simplest way to make a spiral line go through an arbitrary point?

const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');
ctx.strokeStyle = "black";
ctx.lineWidth = 1;
ctx.beginPath();
let last = 1
let start = 1
let i = 0
let origin = [250, 250]
for (let i2 = 0; i2 < 20; i2++) {
ctx.ellipse(...origin, start, start, Math.PI / 2 * i, 0, Math.PI / 2);
i++
i %= 4
if (i == 1) origin[1] -= last
else if (i == 2) origin[0] += last
else if (i == 3) origin[1] += last
else if (i == 0) origin[0] -= last;
[last, start] = [start, start + last]
}
ctx.stroke();
ctx.beginPath()
ctx.lineCap = 'round'
ctx.lineWidth = 7
ctx.strokeStyle = "red";
ctx.lineTo(400, 400)
ctx.stroke()
<canvas width="500" height="500" style="border:1px solid #000000;"></canvas>
What is the simplest way to make the spiral line go through an arbitrary point in the canvas? For example 400x 400y. I think adjusting the initial start and last values based on some calculation could work. The only difference between the first code snippet and the second one is the initial last and start variables. Other solutions that rewrite the entire thing are welcome too.
const canvas = document.querySelector( 'canvas' );
const ctx = canvas.getContext( '2d' );
ctx.strokeStyle = "black";
ctx.lineWidth = 1;
ctx.beginPath();
let last = 0.643
let start = 0.643
let i = 0
let origin = [250,250]
for (let i2=0; i2<20; i2++) {
ctx.ellipse(...origin, start, start, Math.PI/2 *i , 0, Math.PI /2);
i++
i%=4
if (i==1) origin[1] -= last
if (i==2) origin[0] += last
if (i==3) origin[1] += last
if (i==0) origin[0] -= last
;[last, start] = [start, start + last]
}
ctx.stroke();
ctx.beginPath()
ctx.lineCap = 'round'
ctx.lineWidth = 7
ctx.strokeStyle = "red";
ctx.lineTo(400, 400)
ctx.stroke()
<canvas width="500" height="500" style="border:1px solid #000000;"></canvas>
I am not sure how you want the spiral to intercept the point. There are twp options.
Rotate the spiral to intercept point
Scale the spiral to intercept point
This answer solves using method 1. Method 2 has some problems as the number of turns can grow exponentially making the rendering very slow if we don't set limits to where the point of intercept can be.
Not a spiral
The code you provided does not draw a spiral in the mathematical definition but rather is just a set of connected ellipsoids.
This means that there is more than one function that defines a point on these connected curves. To solve for a point will require some complexity as each possible curve must be solved and the solution then vetted to locate the correct curve. On top of that ellipsoids I find to result in some very ugly math.
A spiral function
If we define the curve as just one function where the spiral radius is defined by the angle, it is then very easy to solve.
The function for the radius can be a simplified polynomial in the form Ax^P+C where x is the angle, P is the spiralness (for want of a better term), A is the scale (again for want of a better term) and C is the start angle
C is there if you want to make the step angle of the spiral be a set length eg 1 px would be angle += 1 / (Ax^P+C) If C is 0 then 1/0 would result in an infinite loop.
Drawing the spiral
As defined above there are many types of spirals that can be rendered so there should be one that is close to the spiral you have.
Any point on the spiral is found as follows
x = cos(angle) * f(angle) + origin.x
y = sin(angle) * f(angle) + origin.y
where f is the poly f(x) = Ax^P+C
The following function draws a basic linear spiral f(x) = 1*x^1+0.1
function drawSpiral(origin) {
ctx.strokeStyle = "black";
ctx.lineWidth = 3;
ctx.beginPath();
let i = 0;
while (i < 5) {
const r = i + 0.1; // f(x) = 1*x^1+0.1
ctx.lineTo(
Math.cos(i) * r + origin.x,
Math.sin(i) * r + origin.y
);
i += 0.1
}
ctx.stroke();
}
Solve to pass though point
To solve for a point we convert the point to a polar coordinate relative to the origin. See functions pointDist , pointAngle. We then solve for Ax^P+C = dist in terms of x (the angle) and dist the distance from the origin. Then subtract the angle to the point to get the spirals orientation. (NOTE ^ means to power of, rest of answer uses JavaScripts **)
To solve an arbitrary polynomial can become rather complex that is why I used the simplified version.
The function A * x ** P + C = pointDist(point) needs to be rearranged in terms of pointDist(point).
This gives x = ((pointDist(point) - C) / A) ** (1 / P)
And then subtract the polar angle x = ((pointDist(point)- C) / A) ** (1 / P) - pointAngle(point) and we have the angle offset so that the spiral will intercept the point.
Example
A working example in case the above was TLDR or had too much math like jargon.
The example defines a spiral via the coefficients of the radius function A, C, and P.
There are 3 example spirals Black, Blue, and Green.
A spiral is drawn until its radius is greater than the diagonal distance to the canvas corner. The origin is the center of the canvas.
The point to intercept is set by the mouse position over the page.
The spirals are only rendered when the mouse position changes.
The solution for the simplified polynomial is shown in steps in the function startAngle.
While I wrote the code I seam to have lost the orientation and thus needed to add 180 deg to the start angle (Math.PI) or the point ends up midway between spiral arms.
const ctx = canvas.getContext("2d");
const mouse = {x : 0, y : 0}, mouseOld = {x : undefined, y : undefined};
document.addEventListener("mousemove", (e) => { mouse.x = e.pageX; mouse.y = e.pageY });
requestAnimationFrame(loop);
const TURNS = 4 * Math.PI * 2;
let origin = {x: canvas.width / 2, y: canvas.height / 2};
scrollTo(0, origin.y - innerHeight / 2);
const maxRadius = (origin.x ** 2 + origin.y ** 2) ** 0.5; // dist from origin to corner
const pointDist = (p1, p2) => Math.hypot(p1.x - p2.x, p1.y - p2.y);
const pointAngle = (p1, p2) => Math.atan2(p1.y - p2.y, p1.x - p2.x);
const radius = (x, spiral) => spiral.A * x ** spiral.P + spiral.C;
const startAngle = (origin, point, spiral) => {
const dist = pointDist(origin, point);
const ang = pointAngle(origin, point);
// Da math
// from radius function A * x ** P + C
// where x is ang
// A * x ** P + C = dist
// A * x ** P = dist - C
// x ** P = (dist - C) / A
// x = ((dist - C) / A) ** (1 / p)
return ((dist - spiral.C) / spiral.A) ** (1 / spiral.P) - ang;
}
// F for Fibonacci
const startAngleF = (origin, point, spiral) => {
const dist = pointDist(origin, point);
const ang = pointAngle(origin, point);
return (1 / spiral.P) * Math.log(dist / spiral.A) - ang;
}
const radiusF = (x, spiral) => spiral.A * Math.E ** (spiral.P * x);
const spiral = (P, A, C, rFc = radius, aFc = startAngle) => ({P, A, C, rFc, aFc});
const spirals = [
spiral(2, 1, 0.1),
spiral(3, 0.25, 0.1),
spiral(0.3063489,0.2972713047, null, radiusF, startAngleF),
spiral(0.8,4, null, radiusF, startAngleF),
];
function drawSpiral(origin, point, spiral, col) {
const start = spiral.aFc(origin, point, spiral);
ctx.strokeStyle = col;
ctx.beginPath();
let i = 0;
while (i < TURNS) {
const r = spiral.rFc(i, spiral);
const ang = i - start - Math.PI;
ctx.lineTo(
Math.cos(ang) * r + origin.x,
Math.sin(ang) * r + origin.y
);
if (r > maxRadius) { break }
i += 0.1
}
ctx.stroke();
}
loop()
function loop() {
if (mouse.x !== mouseOld.x || mouse.y !== mouseOld.y) {
ctx.clearRect(0, 0, 500, 500);
ctx.lineWidth = 1;
drawSpiral(origin, mouse, spirals[0], "#FFF");
drawSpiral(origin, mouse, spirals[1], "#0FF");
ctx.lineWidth = 4;
drawSpiral(origin, mouse, spirals[2], "#FF0");
drawSpiral(origin, mouse, spirals[3], "#AF0");
ctx.beginPath();
ctx.lineCap = "round";
ctx.lineWidth = 7;
ctx.strokeStyle = "red";
ctx.lineTo(mouse.x, mouse.y);
ctx.stroke();
Object.assign(mouseOld, mouse);
}
requestAnimationFrame(loop);
}
canvas { position : absolute; top : 0px; left : 0px; background: black }
<canvas id="canvas" width = "500" height = "500"></canvas>
UPDATE
As requested in the comments
I have added the Fibonacci spiral to the example
The radius function is radiusF
The function to find the start angle to intercept a point is startAngleF
The two new Fibonacci spirals are colored limeGreen and Yellow
To use the Fibonacci spiral you must include the functions radiusF and startAngleF when defining the spiral eg spiral(1, 1, 0, radiusF, startAngleF)
Note the 3rd argument is not used and is zero in the eg above. as I don't think you will need it

How to draw herringbone pattern on html canvas

I Have to draw Herringbone pattern on canvas and fill with image
some one please help me I am new to canvas 2d drawing.
I need to draw mixed tiles with cross pattern (Herringbone)
var canvas = this.__canvas = new fabric.Canvas('canvas');
var canvas_objects = canvas._objects;
// create a rectangle with a fill and a different color stroke
var left = 150;
var top = 150;
var x=20;
var y=40;
var rect = new fabric.Rect({
left: left,
top: top,
width: x,
height: y,
angle:45,
fill: 'rgba(255,127,39,1)',
stroke: 'rgba(34,177,76,1)',
strokeWidth:0,
originX:'right',
originY:'top',
centeredRotation: false
});
canvas.add(rect);
for(var i=0;i<15;i++){
var rectangle = fabric.util.object.clone(getLastobject());
if(i%2==0){
rectangle.left = rectangle.oCoords.tr.x;
rectangle.top = rectangle.oCoords.tr.y;
rectangle.originX='right';
rectangle.originY='top';
rectangle.angle =-45;
}else{
fabric.log('rectangle: ', rectangle.toJSON());
rectangle.left = rectangle.oCoords.tl.x;
rectangle.top = rectangle.oCoords.tl.y;
fabric.log('rectangle: ', rectangle.toJSON());
rectangle.originX='left';
rectangle.originY='top';
rectangle.angle =45;
}
//rectangle.angle -90;
canvas.add(rectangle);
}
fabric.log('rectangle: ', canvas.toJSON());
canvas.renderAll();
function getLastobject(){
var last = null;
if(canvas_objects.length !== 0){
last = canvas_objects[canvas_objects.length -1]; //Get last object
}
return last;
}
How to draw this pattern in canvas using svg or 2d,3d method. If any third party library that also Ok for me.
I don't know where to start and how to draw this complex pattern.
some one please help me to draw this pattern with rectangle fill with dynamic color on canvas.
Here is a sample of the output I need: (herringbone pattern)
I tried something similar using fabric.js library here is my JSFiddle
Trippy disco flooring
To get the pattern you need to draw rectangles one horizontal tiled one space left or right for each row down and the same for the vertical rectangle.
The rectangle has an aspect of width 2 time height.
Drawing the pattern is simple.
Rotating is easy as well the harder part is finding where to draw the tiles for the rotation.
To do that I create a inverse matrix of the rotation (it reverses a rotation). I then apply that rotation to the 4 corners of the canvas 0,0, width,0 width,height and 0,height this gives me 4 points in the rotated space that are at the edges of the canvas.
As I draw the tiles from left to right top to bottom I find the min corners for the top left, and the max corners for the bottom right, expand it out a little so I dont miss any pixels and draw the tiles with a transformation set the the rotation.
As I could not workout what angle you wanted it at the function will draw it at any angle. On is animated, the other is at 60deg clockwise.
Warning demo contains flashing content.
Update The flashing was way to out there, so have made a few changes, now colours are a more pleasing blend and have fixed absolute positions, and have tied the tile origin to the mouse position, clicking the mouse button will cycle through some sizes as well.
const ctx = canvas.getContext("2d");
const colours = []
for(let i = 0; i < 1; i += 1/80){
colours.push(`hsl(${Math.floor(i * 360)},${Math.floor((Math.sin(i * Math.PI *4)+1) * 50)}%,${Math.floor(Math.sin(i * Math.PI *8)* 25 + 50)}%)`)
}
const sizes = [0.04,0.08,0.1,0.2];
var currentSize = 0;
const origin = {x : canvas.width / 2, y : canvas.height / 2};
var size = Math.min(canvas.width * 0.2, canvas.height * 0.2);
function drawPattern(size,origin,ang){
const xAx = Math.cos(ang); // define the direction of xAxis
const xAy = Math.sin(ang);
ctx.setTransform(1,0,0,1,0,0);
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.setTransform(xAx,xAy,-xAy,xAx,origin.x,origin.y);
function getExtent(xAx,xAy,origin){
const im = [1,0,0,1]; // inverse matrix
const dot = xAx * xAx + xAy * xAy;
im[0] = xAx / dot;
im[1] = -xAy / dot;
im[2] = xAy / dot;
im[3] = xAx / dot;
const toWorld = (x,y) => {
var point = {};
var xx = x - origin.x;
var yy = y - origin.y;
point.x = xx * im[0] + yy * im[2];
point.y = xx * im[1] + yy * im[3];
return point;
}
return [
toWorld(0,0),
toWorld(canvas.width,0),
toWorld(canvas.width,canvas.height),
toWorld(0,canvas.height),
]
}
const corners = getExtent(xAx,xAy,origin);
var startX = Math.min(corners[0].x,corners[1].x,corners[2].x,corners[3].x);
var endX = Math.max(corners[0].x,corners[1].x,corners[2].x,corners[3].x);
var startY = Math.min(corners[0].y,corners[1].y,corners[2].y,corners[3].y);
var endY = Math.max(corners[0].y,corners[1].y,corners[2].y,corners[3].y);
startX = Math.floor(startX / size) - 2;
endX = Math.floor(endX / size) + 2;
startY = Math.floor(startY / size) - 2;
endY = Math.floor(endY / size) + 2;
// draw the pattern
ctx.lineWidth = size * 0.1;
ctx.lineJoin = "round";
ctx.strokeStyle = "black";
var colourIndex = 0;
for(var y = startY; y <endY; y+=1){
for(var x = startX; x <endX; x+=1){
if((x + y) % 4 === 0){
colourIndex = Math.floor(Math.abs(Math.sin(x)*size + Math.sin(y) * 20));
ctx.fillStyle = colours[(colourIndex++)% colours.length];
ctx.fillRect(x * size,y * size,size * 2,size);
ctx.strokeRect(x * size,y * size,size * 2,size);
x += 2;
ctx.fillStyle = colours[(colourIndex++)% colours.length];
ctx.fillRect(x * size,y * size, size, size * 2);
ctx.strokeRect(x * size,y * size, size, size * 2);
x += 1;
}
}
}
}
// Animate it all
var update = true; // flag to indecate something needs updating
function mainLoop(time){
// if window size has changed update canvas to new size
if(canvas.width !== innerWidth || canvas.height !== innerHeight || update){
canvas.width = innerWidth;
canvas.height = innerHeight
origin.x = canvas.width / 2;
origin.y = canvas.height / 2;
size = Math.min(canvas.width, canvas.height) * sizes[currentSize % sizes.length];
update = false;
}
if(mouse.buttonRaw !== 0){
mouse.buttonRaw = 0;
currentSize += 1;
update = true;
}
// draw the patter
drawPattern(size,mouse,time/2000);
requestAnimationFrame(mainLoop);
}
requestAnimationFrame(mainLoop);
mouse = (function () {
function preventDefault(e) { e.preventDefault() }
var m; // alias for mouse
var mouse = {
x : 0, y : 0, // mouse position
buttonRaw : 0,
over : false, // true if mouse over the element
buttonOnMasks : [0b1, 0b10, 0b100], // mouse button on masks
buttonOffMasks : [0b110, 0b101, 0b011], // mouse button off masks
bounds : null,
eventNames : "mousemove,mousedown,mouseup,mouseout,mouseover".split(","),
event(e) {
var t = e.type;
m.bounds = m.element.getBoundingClientRect();
m.x = e.pageX - m.bounds.left - scrollX;
m.y = e.pageY - m.bounds.top - scrollY;
if (t === "mousedown") { m.buttonRaw |= m.buttonOnMasks[e.which - 1] }
else if (t === "mouseup") { m.buttonRaw &= m.buttonOffMasks[e.which - 1] }
else if (t === "mouseout") { m.over = false }
else if (t === "mouseover") { m.over = true }
e.preventDefault();
},
start(element) {
if (m.element !== undefined) { m.remove() }
m.element = element === undefined ? document : element;
m.eventNames.forEach(name => document.addEventListener(name, mouse.event) );
document.addEventListener("contextmenu", preventDefault, false);
},
}
m = mouse;
return mouse;
})();
mouse.start(canvas);
canvas {
position : absolute;
top : 0px;
left : 0px;
}
<canvas id=canvas></canvas>
Un-animated version at 60Deg
const ctx = canvas.getContext("2d");
const colours = ["red","green","yellow","orange","blue","cyan","magenta"]
const origin = {x : canvas.width / 2, y : canvas.height / 2};
var size = Math.min(canvas.width * 0.2, canvas.height * 0.2);
function drawPattern(size,origin,ang){
const xAx = Math.cos(ang); // define the direction of xAxis
const xAy = Math.sin(ang);
ctx.setTransform(1,0,0,1,0,0);
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.setTransform(xAx,xAy,-xAy,xAx,origin.x,origin.y);
function getExtent(xAx,xAy,origin){
const im = [1,0,0,1]; // inverse matrix
const dot = xAx * xAx + xAy * xAy;
im[0] = xAx / dot;
im[1] = -xAy / dot;
im[2] = xAy / dot;
im[3] = xAx / dot;
const toWorld = (x,y) => {
var point = {};
var xx = x - origin.x;
var yy = y - origin.y;
point.x = xx * im[0] + yy * im[2];
point.y = xx * im[1] + yy * im[3];
return point;
}
return [
toWorld(0,0),
toWorld(canvas.width,0),
toWorld(canvas.width,canvas.height),
toWorld(0,canvas.height),
]
}
const corners = getExtent(xAx,xAy,origin);
var startX = Math.min(corners[0].x,corners[1].x,corners[2].x,corners[3].x);
var endX = Math.max(corners[0].x,corners[1].x,corners[2].x,corners[3].x);
var startY = Math.min(corners[0].y,corners[1].y,corners[2].y,corners[3].y);
var endY = Math.max(corners[0].y,corners[1].y,corners[2].y,corners[3].y);
startX = Math.floor(startX / size) - 4;
endX = Math.floor(endX / size) + 4;
startY = Math.floor(startY / size) - 4;
endY = Math.floor(endY / size) + 4;
// draw the pattern
ctx.lineWidth = 5;
ctx.lineJoin = "round";
ctx.strokeStyle = "black";
for(var y = startY; y <endY; y+=1){
for(var x = startX; x <endX; x+=1){
ctx.fillStyle = colours[Math.floor(Math.random() * colours.length)];
if((x + y) % 4 === 0){
ctx.fillRect(x * size,y * size,size * 2,size);
ctx.strokeRect(x * size,y * size,size * 2,size);
x += 2;
ctx.fillStyle = colours[Math.floor(Math.random() * colours.length)];
ctx.fillRect(x * size,y * size, size, size * 2);
ctx.strokeRect(x * size,y * size, size, size * 2);
x += 1;
}
}
}
}
canvas.width = innerWidth;
canvas.height = innerHeight
origin.x = canvas.width / 2;
origin.y = canvas.height / 2;
size = Math.min(canvas.width * 0.2, canvas.height * 0.2);
drawPattern(size,origin,Math.PI / 3);
canvas {
position : absolute;
top : 0px;
left : 0px;
}
<canvas id=canvas></canvas>
The best way to approach this is to examine the pattern and analyse its symmetry and how it repeats.
You can look at this several ways. For example, you could rotate the patter 45 degrees so that the tiles are plain orthogonal rectangles. But let's just look at it how it is. I am going to assume you are happy with it with 45deg tiles.
Like the tiles themselves, it turns out the pattern has a 2:1 ratio. If we repeat this pattern horizontally and vertically, we can fill the canvas with the completed pattern.
We can see there are five tiles that overlap with our pattern block. However we don't need to draw them all when we draw each pattern block. We can take advantage of the fact that blocks are repeated, and we can leave the drawing of some tiles to later rows and columns.
Let's assume we are drawing the pattern blocks from left to right and top to bottom. Which tiles do we need to draw, at a minimum, to ensure this pattern block gets completely drawn (taking into account adjacent pattern blocks)?
Since we will be starting at the top left (and moving right and downwards), we'll need to draw tile 2. That's because that tile won't get drawn by either the block below us, or the block to the right of us. The same applies to tile 3.
It turns out those two are all we'll need to draw for each pattern block. Tile 1 and 4 will be drawn when the pattern block below us draws their tile 2 and 3 respectively. Tile 5 will be drawn when the pattern block to the south-east of us draws their tile 1.
We just need to remember that we may need to draw an extra column on the right-hand side, and at the bottom, to ensure those end-of-row and end-of-column pattern blocks get completely drawn.
The last thing to work out is how big our pattern blocks are.
Let's call the short side of the tile a and the long side b. We know that b = 2 * a. And we can work out, using Pythagoras Theorem, that the height of the pattern block will be:
h = sqrt(a^2 + a^2)
= sqrt(2 * a^2)
= sqrt(2) * a
The width of the pattern block we can see will be w = 2 * h.
Now that we've worked out how to draw the pattern, let's implement our algorithm.
const a = 60;
const b = 120;
const h = 50 * Math.sqrt(2);
const w = h * 2;
const h2 = h / 2; // How far tile 1 sticks out to the left of the pattern block
// Set of colours for the tiles
const colours = ["red","cornsilk","black","limegreen","deepskyblue",
"mediumorchid", "lightgrey", "grey"]
const canvas = document.getElementById("herringbone");
const ctx = canvas.getContext("2d");
// Set a universal stroke colour and width
ctx.strokeStyle = "black";
ctx.lineWidth = 4;
// Loop through the pattern block rows
for (var y=0; y < (canvas.height + h); y+=h)
{
// Loop through the pattern block columns
for (var x=0; x < (canvas.width + w); x+=w)
{
// Draw tile "2"
// I'm just going to draw a path for simplicity, rather than
// worrying about drawing a rectangle with rotation and translates
ctx.beginPath();
ctx.moveTo(x - h2, y - h2);
ctx.lineTo(x, y - h);
ctx.lineTo(x + h, y);
ctx.lineTo(x + h2, y + h2);
ctx.closePath();
ctx.fillStyle = colours[Math.floor(Math.random() * colours.length)];
ctx.fill();
ctx.stroke();
// Draw tile "3"
ctx.beginPath();
ctx.moveTo(x + h2, y + h2);
ctx.lineTo(x + w - h2, y - h2);
ctx.lineTo(x + w, y);
ctx.lineTo(x + h, y + h);
ctx.closePath();
ctx.fillStyle = colours[Math.floor(Math.random() * colours.length)];
ctx.fill();
ctx.stroke();
}
}
<canvas id="herringbone" width="500" height="400"></canvas>

HTML5 Canvas - How to move an object in a direction?

I have an object I want to make orbit a star. I've managed to make the object move towards the star, but now I need to set up lateral movement as well.
Obviously this isn't as easy as just adjusting X, as when it moves round to the side of the star I'll have to adjust Y as well. I'm wondering how I could use some math to figure out how much I need to adjust X and Y by as the object moves around the star.
Here's my code so far:
var c = document.getElementById('canvas');
var ctx = c.getContext('2d');
c.width = window.innerWidth;
c.height = window.innerHeight;
var star = {
x: c.width / 2,
y: c.height / 2,
r: 100,
g: 2,
draw: function()
{
ctx.beginPath();
ctx.arc(this.x, this.y, this.r, 0, 2*Math.PI);
ctx.fillStyle = 'orange';
ctx.fill();
ctx.closePath();
}
};
var node = {
x: c.width / 2,
y: 100,
r: 20,
draw: function()
{
ctx.beginPath();
ctx.arc(this.x, this.y, this.r, 0, 2*Math.PI);
ctx.fillStyle = 'blue';
ctx.fill();
ctx.closePath();
}
};
//GAME LOOP
function gameLoop()
{
update();
render();
window.requestAnimationFrame(gameLoop);
}
function update()
{
//Move towards star
var dx = star.x - node.x;
var dy = star.y - node.y;
var angle = Math.atan2(dy, dx);
node.x += Math.cos(angle);
node.y += Math.sin(angle);
//Lateral movement
node.x += 2;
}
function render()
{
ctx.clearRect(0, 0, c.width, c.height);
star.draw();
node.draw();
}
window.requestAnimationFrame(gameLoop);
<html>
<head>
<style>
body
{
margin: 0;
padding: 0;
overflow: hidden;
}
#canvas
{
background-color: #001319;
}
</style>
</head>
<body>
<canvas id="canvas">
</canvas>
<script src="Orbit.js"></script>
</body>
</html>
Newton's and Kepler's clockwork universe
When Newton worked out the maths for calculating orbits he noted something that prompted him to coin the term "clockwork universe". In a two body simulation the orbital paths of both objects repeat precisely. This mean that both objects will at the same time be in the exact same position at the exact same speed they were in the last orbit, there will be no precession.
Gravity, force, mass, and distance.
For a more accurate model of gravity you can use the laws of gravity as discovered by Newton. F = G * (m1*m2)/(r*r) where F is force, G is the Gravitational constant (and for simulations it is just a scaling factor) m1,m2 are the mass of each body and r is the distance between the bodies.
Mass of a sphere
We give both the star and planet some mass. Let's say that in the computer 1 pixel cubed is equal to 1 unit mass. Thus the mass of a sphere of radius R is 4/3 * R3 * PI.
Force, mass, and acceleration
The force is always applied along the line between the bodies and is called acceleration.
When a force is applied to an object we use another of Newton's discovered laws, F=ma where a is acceleration. We have the F (force) and m (mass) so now all we need is a. Rearrange F=ma to get a = f/m.
If we look at both formulas in terms of a (acceleration) a = (G * (m1*m2)/(r*r)) / m1 we can see that the mass of the object we are apply force to is cancelled out a = G * (m2)/(r*r). Now we can calculate the acceleration due to gravity. Acceleration is just change in velocity over time, and we know that that change is in the direction of the other body. So we get the vector between the bodies (o1,o2 for object 1 and 2) dx = o2.x-o1.x, dy = o2.y-o1.y Then find the length of that vector (which is the r in the gravity formula) dist = Math.sqrt(dx* dx + dy * dy). Then we normalise the vector (make its length = one) by dividing by its length. dx /= dist, dy /= dist. Calculate the a (acceleration) and multiply the normalised vector between the object by a then add that to the object's velocity and that is it. Perfect Newtonian clockwork orbits (for two bodies that is).
Clean up with Kepler.
All that math is good but it does not make for a nice simulation. When the math is done both objects start moving and if the starting velocities are not in balance then the whole system will slowly drift of the canvas.
We could just make the display relative to one of the bodies, this would eliminate any drift in the system, but we still have the problem of getting an orbit. If one object is moving to fast it will fly off and never come back. If it is going too slow then it will fall in very close to the centerpoint of the other object. If this happens the change in velocity will approch infinity, something computers are not that good at handling.
So to get nice circular orbits we need one last bit of math.
Using Kepler's second law modified to fit into Newton's math we get a formula that will give the approximate (It is an approximate as the actual calculations involve an infinite series and I can not be bothered writing that out.) orbital velocity v = sqrt(G*(m1 + m2)/r). It looks similar to Newton's gravity law but in this the masses are summed not multiplied, and the distance is not squared.
So we use this to calculate the tangential speed of both bodies to give them near circular orbits. It is important that each object go in the opposite direction to each other.
I created a setup function that sets up the correct orbits for both the sun and the planet. But the value of G (Gravitational constant) is likely way to large. To get a better value I scale G (via kludge math) so that the sun's orbit speed is close to a desired ideal sunV (pixels per frame) To make the whole sim run quicker increase this value
As I have set up the code to have more than two bodies the calculation of starting velocity will only work if each object is significantly more massive than the next. I have added a moon (you need to un-comment to see) to the planet, but it is too big and it's starting velocity is a little too low. It gets pulled (gravity sling shot) by the Earth into a higher orbit,. but this also pulls the earth into a lower orbit making its orbit more eccentric
NOTE After all that I find that something is not quite right and there is still a tiny bit of drift in the system. As I am out of time I have just fixed the sun position to keep the system on the canvas.
var c = document.getElementById('canvas');
c.width = innerWidth;
c.height = innerHeight;
var ctx = c.getContext('2d');
const STAR_RADIUS = 100;
const PLANET_RADIUS = 10;
const MOON_RADIUS = 4.5;
var G = 1; // gravitational constant is not so constant as need to
// scale it to find best value for the system.
// for that I will scale it so that the suns orbital speed around the
// planet is approx 0.1 pixels per frame
const sunV = 0.1; // the sun's orbital desired speed. THis is used to tune G
const DRAW = function () {
ctx.beginPath();
ctx.arc(this.x, this.y, this.r, 0, 2*Math.PI);
ctx.fillStyle = this.col;
ctx.fill();
ctx.closePath();
}
var star = {
x: c.width / 2,
y: c.height / 2,
vx : 0,
vy : 0,
r: STAR_RADIUS,
mass : (4/3) * Math.pow(STAR_RADIUS,3) * Math.PI,
col : 'orange',
draw : DRAW,
};
// kludge to fix drift
const sunStartX = star.x;
const sunStartY = star.y;
var node = {
x: c.width / 2 - STAR_RADIUS - PLANET_RADIUS * 5,
y: c.height / 2,
r: PLANET_RADIUS,
mass : (4/3) * Math.pow(PLANET_RADIUS,3) * Math.PI,
col : "blue",
draw : DRAW,
vx: -1,
vy: 0,
};
var moon = {
x: c.width / 2- STAR_RADIUS - PLANET_RADIUS * 7 ,
y: c.height / 2,
r: MOON_RADIUS,
mass : (4/3) * Math.pow(PLANET_RADIUS,3) * Math.PI,
col : "#888",
draw : DRAW,
vx: -1,
vy: 0,
};
const objects = [star, node];//, moon];
function setup(){
var dist,dx,dy,o1,o2,v,c,dv;
o1 = objects[0];
o1.vx = 0;
o1.vy = 0;
for(var j = 0; j < objects.length; j ++){
if(j !== 0){ // object can not apply force to them selves
o2 = objects[j];
dx = o2.x - o1.x;
dy = o2.y - o1.y;
dist = Math.sqrt(dx * dx + dy * dy);
dx /= dist;
dy /= dist;
// Find value og G
if(j === 1){ // is this not sun
v = Math.sqrt(G * ( o2.mass ) / dist);
dv = sunV - v;
while(Math.abs(dv) > sunV * sunV){
if(dv < 0){ // sun too fast
G *= 0.75;
}else{
G += G * 0.1;
}
v = Math.sqrt(G * ( o2.mass ) / dist);
dv = sunV - v;
}
}
v = Math.sqrt(G * ( o2.mass ) / dist);
o1.vx -= v * dy; // along the tangent
o1.vy += v * dx;
}
}
for(var i = 1; i < objects.length; i ++){
o1 = objects[i];
o1.vx = 0;
o1.vy = 0;
for(var j = 0; j <objects.length; j ++){
if(j !== i){
o2 = objects[j];
dx = o2.x - o1.x;
dy = o2.y - o1.y;
dist = Math.sqrt(dx * dx + dy * dy);
dx /= dist;
dy /= dist;
v = Math.sqrt(G * ( o2.mass ) / dist);
o1.vx += v * dy; // along the tangent
o1.vy -= v * dx;
}
}
}
}
//GAME LOOP
function gameLoop(){
update();
render();
requestAnimationFrame(gameLoop);
}
// every object exerts a force on every other object
function update(){
var dist,dx,dy,o1,o2,a;
// find force of acceleration each object applies to each object
for(var i = 0; i < objects.length; i ++){
o1 = objects[i];
for(var j = 0; j < objects.length; j ++){
if(i !== j){ // object can not apply force to them selves
o2 = objects[j];
dx = o2.x - o1.x;
dy = o2.y - o1.y;
dist = Math.sqrt(dx * dx + dy * dy);
dx /= dist; // normalise the line between the objects (makes the vector 1 unit long)
dy /= dist;
// get force
a = (G * o2.mass ) / (dist * dist);
o1.vx += a * dx;
o1.vy += a * dy;
}
}
}
// once all the forces have been found update objects positions
for(var i = 0; i < objects.length; i ++){
o1 = objects[i];
o1.x += o1.vx;
o1.y += o1.vy;
}
}
function render(){
ctx.clearRect(0, 0, c.width, c.height);
// kludge to fix drift
var offsetX = objects[0].x - sunStartX;
var offsetY = objects[0].y - sunStartY;
ctx.setTransform(1,0,0,1,-offsetX,-offsetY);
for(var i = 0; i < objects.length; i ++){
objects[i].draw();
}
ctx.setTransform(1,0,0,1,0,0);
}
setup();
requestAnimationFrame(gameLoop);
<canvas id='canvas'></canvas>
Okay, I've answered my own question.
Rather than making the star's gravity directly affect the x and y coordinates, I have a vx and vy of the object, and I cause the gravity to affect that value, and then just adjust x and y by vx and vy on each update.
Here's the code:
var c = document.getElementById('canvas');
var ctx = c.getContext('2d');
c.width = window.innerWidth;
c.height = window.innerHeight;
var star = {
x: c.width / 2,
y: c.height / 2,
r: 100,
g: 0.5,
draw: function()
{
ctx.beginPath();
ctx.arc(this.x, this.y, this.r, 0, 2*Math.PI);
ctx.fillStyle = 'orange';
ctx.fill();
ctx.closePath();
}
};
var node = {
x: c.width / 2,
y: 50,
r: 20,
vx: 15,
vy: 0,
draw: function()
{
ctx.beginPath();
ctx.arc(this.x, this.y, this.r, 0, 2*Math.PI);
ctx.fillStyle = 'blue';
ctx.fill();
ctx.closePath();
}
};
//GAME LOOP
function gameLoop()
{
update();
render();
window.requestAnimationFrame(gameLoop);
}
function update()
{
node.x += node.vx;
node.y += node.vy;
//Move towards star
var dx = star.x - node.x;
var dy = star.y - node.y;
var angle = Math.atan2(dy, dx);
node.vx += (Math.cos(angle) * star.g);
node.vy += (Math.sin(angle) * star.g);
}
function render()
{
ctx.clearRect(0, 0, c.width, c.height);
star.draw();
node.draw();
}
window.requestAnimationFrame(gameLoop);
<canvas id='canvas'></canvas>

Animating a section of a path using canvas

I'm trying to animate a section of a path using canvas. Basically I have a straight line that runs through three links. When you hover over a link the section of the path behind the link should animate into a sine wave.
I have no problem animating the whole path into the shape of a sine wave but when it comes to animating a section of a path, I'm at a loss :(
I've attached a reference image below to give an idea of what it is I'm trying to achieve.
Below is jsfiddle of the code I'm currently using to animate the path. I'm a canvas noob so forgive me if it awful...
https://jsfiddle.net/9mu8xo0L/
and here is the code:
class App {
constructor() {
this.drawLine();
}
drawLine() {
this.canvas = document.getElementById('sine-wave');
this.canvas.width = 1000;
this.ctx = this.canvas.getContext("2d");
this.cpY = 0;
this.movement = 1;
this.fps = 60;
this.ctx.moveTo(0, 180);
this.ctx.lineTo(1000, 180);
this.ctx.stroke();
this.canvas.addEventListener('mouseover', this.draw.bind(this));
}
draw() {
setTimeout(() => {
if (this.cpY >= 6) return;
requestAnimationFrame(this.draw.bind(this));
// animate the control point
this.cpY += this.movement;
const increase = (90 / 180) * (Math.PI / 2);
let counter = 0;
let x = 0;
let y = 180;
this.ctx.beginPath();
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
for(let i = 0; i <= this.canvas.width; i += 6) {
this.ctx.moveTo(x,y);
x = i;
y = 180 - Math.sin(counter) * this.cpY;
counter += increase;
this.ctx.lineTo(x, y);
this.ctx.stroke();
}
}, 1000 / this.fps);
}
}
Simply split the drawing of the line in three parts, drawing 1/3 as straight line, animate the mid section and add the last 1/3.
I'll demonstrate the first 1/3 + animation and leave the last 1/3 as an exercise (also moved the stroke() outside the loop so it doesn't overdraw per segment) - there is room for refactoring and optimizations here but I have not addressed that in this example -
let x = this.canvas.width / 3; // start of part 2 (animation)
let y = 180;
this.ctx.beginPath();
this.ctx.clearRect(0, x, this.canvas.width, this.canvas.height);
// draw first 1/3
this.ctx.moveTo(0, y);
this.ctx.lineTo(x, y);
// continue with part 2
for(let i = x; i <= this.canvas.width; i += 6) {
x = i;
y = 180 - Math.sin(counter) * this.cpY;
counter += increase;
// add to 2. segment
this.ctx.lineTo(x, y);
}
// stroke line
this.ctx.stroke();
Modified fiddle

Categories

Resources