I'm trying to zoom at mouse position, like say on google maps. It kind of works but it shifts the point i want to zoom in on wherever it matches up with the original.Then when i zoom at that point it works fine. I think I need to translate the point back to the mouse, but I'm not sure how to do it exactly.
This is the code before i draw:
translate(zoomLocation.x, zoomLocation.y);
scale(zoom);
translate(-zoomLocation.x, -zoomLocation.y);
drawGrid();
And this is when I zoom:
event.preventDefault();
zoomLocation = {
x: zoomLocation.x + (mouseX - zoomLocation.x) / zoom,
y: zoomLocation.y + (mouseY - zoomLocation.y) / zoom
};
zoom -= zoomSensitivity * event.delta;
let colors = {
background: 0,
gridLines: "white"
};
let nVariables = 4;
let zoom = 1;
let zoomLocation = {
x: 0,
y: 0
};
let zoomSensitivity = 0.0002;
function draw() {
translate(zoomLocation.x, zoomLocation.y);
scale(zoom);
translate(-zoomLocation.x, -zoomLocation.y);
drawGrid();
stroke("blue");
ellipse(zoomLocation.x + (mouseX - zoomLocation.x) / zoom, zoomLocation.y + (mouseY - zoomLocation.y) / zoom, 10, 10);
stroke("red");
ellipse(zoomLocation.x, zoomLocation.y, 10, 10);
}
function setup() {
zoomLocation = {
x: 0,
y: windowHeight / 2
}
createCanvas(windowWidth, windowHeight);
}
function mouseWheel(event) {
event.preventDefault();
let oldZoom = zoom;
zoomLocation = {
x: zoomLocation.x + (mouseX - zoomLocation.x) / zoom,
y: zoomLocation.y + (mouseY - zoomLocation.y) / zoom
};
zoom -= zoomSensitivity * event.delta;
}
function drawGrid() {
let nCells = 2 ** nVariables;
if (nCells > 2048) {
if (!window.confirm(`You are about to create ${nCells} cells. This might lag your browser. Are you sure?`)) {
return;
}
}
background(colors.background);
let gridWidth = windowWidth - 2;
let gridHeight = min(gridWidth / nCells, windowHeight / 2 - 2);
let gridY = windowHeight / 2;
stroke(colors.gridLines);
line(0, gridY, gridWidth, gridY);
line(0, gridY + gridHeight, gridWidth, gridY + gridHeight);
for (let i = 0; i < nCells + 1; i++) {
line(i * (gridWidth / nCells), gridY, i * (gridWidth / nCells), gridY + gridHeight)
}
let curveHeight = 2;
let drawVariable = (n) => {
let p1 = {
x: 1 / (2 ** (n + 1)) * gridWidth,
y: gridY
};
let c1 = {
x: p1.x,
y: p1.y + gridWidth / (2 ** n) * curveHeight
};
let p2 = {
y: p1.y
};
let c2 = {
y: c1.y
};;
noFill();
stroke("red");
if (n == 0) {
p2.x = gridWidth;
c2.x = p2.x;
c1.y = c2.y = p1.y + gridWidth / 2 * curveHeight;
curve(c1.x, c1.y, p1.x, p1.y, p2.x, p2.y, c2.x, c2.y);
return;
}
for (let i = 3; i < 2 ** (n + 1); i += 2) {
p2.x = i / (2 ** (n + 1)) * gridWidth
c2.x = p2.x;
if ((i - 3) % 4 == 0) {
curve(c1.x, c1.y, p1.x, p1.y, p2.x, p2.y, c2.x, c2.y);
} else {
p1.x = p2.x;
c1.x = c2.x;
}
}
};
for (let i = 0; i < nVariables; i++) {
drawVariable(i);
}
}
body {
margin: 0
}
button {
outline: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.11/p5.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.11/addons/p5.dom.js"></script>
<script src="https://code.jquery.com/jquery-3.2.1.js" integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE=" crossorigin="anonymous"></script>
What you're looking for is an application of Affine Transformation. Here's an example where I'm applying transformations incrementally to transform + scale at the mouse pointer location for a Google Maps type zoom effect: Zoom Effect in p5.js Web Editor.
This is a good medium article that explains why this works: Zooming at the Mouse Coordinates with Affine Transformations
This is another good article that has some mathematical explanations on how it achieves the effects: Affine Transformations — Pan, Zoom, Skew
Related
In the following p5.js code I'm trying to create 2 separate methods.
centerInWindow() is meant to keep the image centered in the canvas while it's being scaled down after the user clicks on the canvas.
centerToClick() is meant to keep the image centered on the point the user clicked on, while it's being scaled up.
None of them work and I'm having trouble getting the logic right.
function centerInWindow(img) {
let currentSize = img.width * currentScale
imgX = (windowWidth / 2) - (currentSize / 2)
imgY = (windowHeight / 2) - (currentSize / 2)
}
function centerToClick() {
imgX = clickX * currentScale
imgY = clickY * currentScale
}
let minScale = 1
let maxScale = 5
let targetScale = minScale
let currentScale = targetScale
let clickX, clickY, imgX, imgY
let idx = 0
function setup() {
pixelDensity(1)
createCanvas(windowWidth, windowHeight)
preload(IMG_PATHS, IMGS)
frameRate(12)
}
function draw() {
clear()
if (currentScale < targetScale) {
currentScale += 0.05
if (currentScale > targetScale) {
currentScale = targetScale
}
centerToClick()
} else if (currentScale > targetScale) {
currentScale -= 0.05
if (currentScale < targetScale) {
currentScale = targetScale
}
centerInWindow(IMGS[idx])
} else {
centerInWindow(IMGS[idx])
}
scale(currentScale)
image(IMGS[idx], imgX, imgY)
idx++
if (idx === IMGS.length) {
idx = 0
}
}
window.addEventListener('click', function({ clientX, clientY }) {
targetScale = targetScale === maxScale ? minScale : maxScale
clickX = clientX
clickY = clientY
})
See it in action here.
Any help would be appreciated.
There are probably multiple ways to solve this problem, but here's one:
Imaging your viewport is an NxM rectangle, and you are drawing some portion of a scene in within that viewport. In order to zoom in and out you can shift the origin at which you draw that scene and increase or decrease the scale. The tricky part is to make it possible to zoom in and out centered on an arbitrary point within the currently visible portion of the scene, keeping that point in the scene locked to the current point in the viewport.
Given some center point, and a desired scale factor, it is possible to determine the necessary change in the offset of the scene to preserve the position of the center point after scaling.
There's probably some complicated trigonometric proof for how to calculate this, but conveniently it is a simple calculation based on the ratio of the offset of the mouse from the current top left of the scene, to the scaled height of the scene.
x_offset -= (x_center - x_offset) / (N * current_scale) * (N * new_scale - N * current_scale)
y_offset -= (y_center - y_offset) / (M * current_scale) * (M * new_scale - M * current_scale)
Conveniently it is possible to apply this repeatedly as your scale changes and regardless of whether scale is increasing or decreasing.
Here's a sample sketch demonstrating this:
const viewport = { width: 400, height: 300 };
let scaledView = { ...viewport, x: 0, y: 0 };
function setup() {
createCanvas(windowWidth, windowHeight);
viewport.x = (width - viewport.width) / 2;
viewport.y = (height - viewport.height) / 2;
}
function draw() {
background(255);
translate(viewport.x, viewport.y);
push();
translate(scaledView.x, scaledView.y);
scale(scaledView.width / viewport.width, scaledView.height / viewport.height);
// Draw scene
ellipseMode(CENTER);
noStroke();
fill(200);
rect(0, 0, viewport.width, viewport.height);
stroke('blue');
noFill();
strokeWeight(1);
translate(viewport.width / 2, viewport.height / 2);
circle(0, 0, 200);
arc(0, 0, 120, 120, PI * 0.25, PI * 0.75);
strokeWeight(4)
point(-40, -40);
point(40, -40);
pop();
noFill();
stroke(0);
rect(0, 0, viewport.width, viewport.height);
// viewport relative mouse position
let mousePos = { x: mouseX - viewport.x, y: mouseY - viewport.y };
if (mousePos.x >= 0 && mousePos.x <= viewport.width &&
mousePos.y >= 0 && mousePos.y <= viewport.height) {
line(scaledView.x, scaledView.y, mousePos.x, mousePos.y);
let updatedView = keyIsDown(SHIFT) ? getUnZoomedView(mousePos) : getZoomedView(mousePos);
line(scaledView.x, scaledView.y, updatedView.x, updatedView.y);
stroke('red');
rect(updatedView.x, updatedView.y, updatedView.width, updatedView.height);
}
}
function getZoomedView(center) {
return getScaledView(center, 1.1);
}
function getUnZoomedView(center) {
return getScaledView(center, 0.9);
}
function getScaledView(center, factor) {
// the center position relative to the scaled/shifted scene
let viewCenterPos = {
x: center.x - scaledView.x,
y: center.y - scaledView.y
};
// determine how much we will have to shift to keep the position centered
let shift = {
x: map(viewCenterPos.x, 0, scaledView.width, 0, 1),
y: map(viewCenterPos.y, 0, scaledView.height, 0, 1)
};
// calculate the new view dimensions
let updatedView = {
width: scaledView.width * factor,
height: scaledView.height * factor
};
// adjust the x and y offsets according to the shift
updatedView.x = scaledView.x + (updatedView.width - scaledView.width) * -shift.x;
updatedView.y = scaledView.y + (updatedView.height - scaledView.height) * -shift.y;
return updatedView;
}
function mouseClicked() {
// viewport relative mouse position
let mousePos = { x: mouseX - viewport.x, y: mouseY - viewport.y };
if (mousePos.x >= 0 && mousePos.x <= viewport.width &&
mousePos.y >= 0 && mousePos.y <= viewport.height) {
scaledView = keyIsDown(SHIFT) ? getUnZoomedView(mousePos) : getZoomedView(mousePos);
}
}
html, body {
margin: 0;
padding: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script>
We can actually simplify these equations because N and M can be factored out. The previous pseudo code becomes:
x_offset -= ((x_center - x_offset) * (new_scale - current_scale) * N) / (current_scale * N)
And because both the top and bottom are multiplied by N this becomes:
x_offset -= ((x_center - x_offset) * (new_scale - current_scale)) / (current_scale)
Here is an example using your image drawing code:
const IMG_PATHS = [
'https://storage.googleapis.com/www.paulwheeler.us/files/windows-95-desktop-background.jpg'
];
let IMGS = [];
const minScale = 1;
const maxScale = 5;
let targetScale = minScale;
let currentScale = targetScale;
let targetOrigin = {
x: 0,
y: 0
};
let currentOrigin = {
x: 0,
y: 0
};
let idx = 0;
function preloadHelper(pathsToImgs, imgs) {
for (let pathToImg of pathsToImgs) {
loadImage(pathToImg, img => {
imgs.push(img);
})
}
}
// Make sure load images happen from the actual preload() function. p5.js has special logic when these calls happen here to have the sketch wait to start until all the loadXXX class are complete
function preload() {
preloadHelper(IMG_PATHS, IMGS);
}
function setup() {
pixelDensity(1)
createCanvas(windowWidth, windowHeight)
frameRate(12)
}
function draw() {
clear();
/*
if (currentScale < targetScale) {
currentScale += 0.01
} else if (currentScale > targetScale) {
currentScale -= 0.01
} */
// By making all of the changing components part of a vector and normalizing it we can ensure that the we reach our target origin and scale at the same point
let offset = createVector(
targetOrigin.x - currentOrigin.x,
targetOrigin.y - currentOrigin.y,
// Give the change in scale more weight so that it happens at a similar rate to the translation. This is especially noticable when there is little to no offset required
(targetScale - currentScale) * 500
);
if (offset.magSq() > 0.01) {
// Multiplying by a larger number will move faster
offset.normalize().mult(8);
currentOrigin.x += offset.x;
currentOrigin.y += offset.y;
currentScale += offset.z / 500;
// We need to make sure we do not over shoot or targets
if (offset.x > 0 && currentOrigin.x > targetOrigin.x) {
currentOrigin.x = targetOrigin.x;
}
if (offset.x < 0 && currentOrigin.x < targetOrigin.x) {
currentOrigin.x = targetOrigin.x;
}
if (offset.y > 0 && currentOrigin.y > targetOrigin.y) {
currentOrigin.y = targetOrigin.y;
}
if (offset.y < 0 && currentOrigin.y < targetOrigin.y) {
currentOrigin.y = targetOrigin.y;
}
if (offset.z > 0 && currentScale > targetScale) {
currentScale = targetScale;
}
if (offset.z < 0 && currentScale < targetScale) {
currentScale = targetScale;
}
}
translate(currentOrigin.x, currentOrigin.y);
scale(currentScale);
image(IMGS[idx], 0, 0);
}
function mouseClicked() {
targetScale = constrain(
keyIsDown(SHIFT) ? currentScale * 0.9 : currentScale * 1.1,
minScale,
maxScale
);
targetOrigin = getScaledOrigin({
x: mouseX,
y: mouseY
},
currentScale,
targetScale
);
}
function getScaledOrigin(center, currentScale, newScale) {
// the center position relative to the scaled/shifted scene
let viewCenterPos = {
x: center.x - currentOrigin.x,
y: center.y - currentOrigin.y
};
// determine the new origin
let originShift = {
x: viewCenterPos.x / currentScale * (newScale - currentScale),
y: viewCenterPos.y / currentScale * (newScale - currentScale)
};
return {
x: currentOrigin.x - originShift.x,
y: currentOrigin.y - originShift.y
};
}
html,
body {
margin: 0;
padding: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script>
I am trying to create a grid of x/y coordinates in a square pattern, given three points on an x/y plane. A grid like this
This is to be used to drive a gcode generator for moving a tool-head to desired x,y positions on a 3d printer. I need to account for skew and off-alignment of the square, so the grid of x / y points inside the square needs to account for the alignment.
function genGrid (topLeft, btmRight, btmLeft, rows, cols) {
// Generate Grid
// Return array of coordinates like the red dots in the picture I made.
}
[This picture helps explain it better!]
This code did the trick!
<script>
function grid(p1, p2, count) {
pointPerRow = Math.sqrt(count);
p3 = {
x: (p1.x + p2.x + p2.y - p1.y) / 2,
y: (p1.y + p2.y + p1.x - p2.x) / 2
};
p4 = {
x: (p1.x + p2.x + p1.y - p2.y) / 2,
y: (p1.y + p2.y + p2.x - p1.x) / 2
};
edgeLenght = Math.sqrt( (p3.x - p1.x)**2 + (p3.y - p1.y)**2);
vectorH = {
x: (p3.x - p1.x) / edgeLenght,
y: (p3.y - p1.y) / edgeLenght
};
vectorV = {
x: (p4.x - p1.x) / edgeLenght,
y: (p4.y - p1.y) / edgeLenght
};
movingStep = edgeLenght / (pointPerRow -1);
result = {};
for (var i = 0; i < pointPerRow; i++) {
row = {};
point = {
x: p1.x + vectorH.x * movingStep * (i),
y: p1.y + vectorH.y * movingStep * (i),
}
for (var j = 0; j < pointPerRow; j++) {
row[j] = {
x: point.x + vectorV.x * movingStep * (j),
y: point.y + vectorV.y * movingStep * (j),
};
}
result[i] = row;
}
// Debugging
for (var x=0;x < pointPerRow; x++) {
for (var y=0; y < pointPerRow; y++) {
ctx.fillStyle="#000000";
ctx.fillRect(result[x][y].x,result[x][y].y,10,10);
}
}
ctx.fillStyle="#FF0000";
ctx.fillRect(p1.x,p1.y,5,5);
ctx.fillRect(p2.x,p2.y,5,5);
ctx.fillRect(p3.x,p3.y,5,5);
ctx.fillRect(p4.x,p4.y,5,5);
return result;
}
// Create a canvas that extends the entire screen
// and it will draw right over the other html elements, like buttons, etc
var canvas = document.createElement("canvas");
canvas.setAttribute("width", window.innerWidth);
canvas.setAttribute("height", window.innerHeight);
canvas.setAttribute("style", "position: absolute; x:0; y:0;");
document.body.appendChild(canvas);
//Then you can draw a point at (10,10) like this:
var ctx = canvas.getContext("2d");
var grid = grid({x:100, y:50}, {x:200, y:350}, 16);
</script>
I have been creating a clone of agar.io and I don't understand why the circles start vibrating when they touch each other. Below is my code:
var
canvas,
ctx,
width = innerWidth,
height = innerHeight,
mouseX = 0,
mouseY = 0;
var
camera = {
x: 0,
y: 0,
update: function(obj) {
this.x = obj.x - width / 2;
this.y = obj.y - height / 2;
}
},
player = {
defaultMass: 54,
x: 0,
y: 0,
blobs: [],
update: function() {
for (var i = 0; i < this.blobs.length; i++) {
var x = mouseX + camera.x - this.blobs[i].x;
var y = mouseY + camera.y - this.blobs[i].y;
var length = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
var speed = 54 / this.blobs[i].mass;
this.blobs[i].velX = x / length * speed * Math.min(1, Math.pow(x / this.blobs[i].mass, 2));
this.blobs[i].velY = y / length * speed * Math.min(1, Math.pow(x / this.blobs[i].mass, 2));
this.blobs[i].x += this.blobs[i].velX;
this.blobs[i].y += this.blobs[i].velY;
for (var j = 0; j < this.blobs.length; j++) {
if (j != i && this.blobs[i] !== undefined) {
var blob1 = this.blobs[i];
var blob2 = this.blobs[j];
var dist = Math.sqrt(Math.pow(blob2.x - blob1.x, 2) + Math.pow(blob2.y - blob1.y, 2));
if (dist < blob1.mass + blob2.mass) {
if (this.blobs[i].x < this.blobs[j].x) {
this.blobs[i].x--;
} else if (this.blobs[i].x > this.blobs[j].x) {
this.blobs[i].x++;
}
if (this.blobs[i].y < this.blobs[j].y) {
this.blobs[i].y--;
} else if ((this.blobs[i].y > this.blobs[j].y)) {
this.blobs[i].y++;
}
}
}
}
}
this.x += (mouseX - width / 2) / (width / 2) * 1;
this.y += (mouseY - height / 2) / (height / 2) * 1
},
split: function(cell) {
cell.mass /= 2;
this.blobs.push({
x: cell.x,
y: cell.y,
mass: cell.mass
});
},
draw: function() {
for (var i = 0; i < this.blobs.length; i++) {
ctx.fillStyle = "red";
ctx.beginPath();
ctx.arc(-camera.x + this.blobs[i].x, -camera.y + this.blobs[i].y, this.blobs[i].mass, 0, Math.PI * 2);
ctx.fill();
ctx.closePath();
}
}
};
function handleMouseMove(e) {
mouseX = e.clientX;
mouseY = e.clientY;
}
function setup() {
canvas = document.getElementById("game");
ctx = canvas.getContext("2d");
canvas.width = width;
canvas.height = height;
addEventListener("mousemove", handleMouseMove);
player.blobs.push({
x: 0,
y: 0,
mass: player.defaultMass
});
player.blobs.push({
x: 100,
y: 100,
mass: player.defaultMass / 2
});
player.blobs.push({
x: 100,
y: 100,
mass: player.defaultMass * 2
});
var loop = function() {
update();
draw();
requestAnimationFrame(loop);
}
requestAnimationFrame(loop);
}
function update() {
camera.update(player.blobs[0]);
player.update();
}
function draw() {
ctx.fillStyle = "#fff";
ctx.fillRect(0, 0, width, height);
player.draw();
}
setup();
body {
margin: 0;
padding: 0;
}
<canvas id="game">kindly update your browser.</canvas>
Separating circles
Your separation code was not correct. Use the vector between them to get the new pos.
The vector between them
To find if two circles are intercepting find the length of the vector from one to the next
The two circles.
var cir1 = {x : 100, y : 100, r : 120}; // r is the radius
var cir2 = {x : 250, y : 280, r : 150}; // r is the radius
The vector from cir2 to cir1
var vx = cir2.x - cir1.x;
var vy = cir2.y - cir1.y;
The length of the vector
var len = Math.sqrt(x * x + y * y);
// or use the ES6 Math.hypot function
/* var len = Math.hypot(x,y); */
The circles overlap if the sum of the radii is greater than the length of the vector between them
if(cir1.r + cir2.r > len){ // circles overlap
Normalise the vector
If they overlap you need to move one away from the other. There are many ways to do this, the simplest way is to move one circle along the line between them.
First normalise the vector from cir1 to cir2 by dividing by its (vector) length.
vx \= len;
vy \= len;
Note that the length could be zero. If this happens then you will get NaN in further calculations. If you suspect you may get one circle at the same location as another the easiest way to deal with the zero move one circle a little.
// replace the two lines above with
if(len === 0){ // circles are on top of each other
vx = 1; // move the circle (abstracted into the vector)
}else{
vx \= len; // normalise the vector
vy \= len;
}
Move circle/s to just touch
Now you have the normalised vector which is 1 unit long you can make it any length you need by multiplying the two scalars vx, vy with the desired length which in this case is the sum of the two circles radii.
var mx = vx * (cir1.r + cir2.r); // move distance
var my = vy * (cir1.r + cir2.r);
.Only use one of the following methods.
You can now position one of the circles the correct distance so that they just touch
// move cir1
cir1.x = cir2.x - mx;
cir1.y = cir2.y - my;
Or move the second circle
cir2.x = cir1.x + mx;
cir2.y = cir1.y + my;
Or move both circles but you will have to first find the proportional center between the two
var pLen = cir1.r / (cir1.r + cir2.r); // find the ratio of the radii
var cx = cir1.x + pLen * vx * len; // find the proportional center between
var cy = cir1.y + pLen * vy * len; // the two circles
Then move both circles away from that point by their radii
cir1.x = cx - vx * cir1.r; // move circle 1 away from the shared center
cir1.y = cy - vy * cir1.r;
cir2.x = cx + vx * cir2.r; // move circle 2 away from the shared center
cir2.y = cy + vy * cir2.r;
DEMO
Copy of OP's snippet with mods to fix problem by moving the the first circle blob1 away from the second blob2 and assuming they will never be at the same spot (no divide by zero)
var
canvas,
ctx,
width = innerWidth,
height = innerHeight,
mouseX = 0,
mouseY = 0;
var
camera = {
x: 0,
y: 0,
update: function(obj) {
this.x = obj.x - width / 2;
this.y = obj.y - height / 2;
}
},
player = {
defaultMass: 54,
x: 0,
y: 0,
blobs: [],
update: function() {
for (var i = 0; i < this.blobs.length; i++) {
var x = mouseX + camera.x - this.blobs[i].x;
var y = mouseY + camera.y - this.blobs[i].y;
var length = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
var speed = 54 / this.blobs[i].mass;
this.blobs[i].velX = x / length * speed * Math.min(1, Math.pow(x / this.blobs[i].mass, 2));
this.blobs[i].velY = y / length * speed * Math.min(1, Math.pow(x / this.blobs[i].mass, 2));
this.blobs[i].x += this.blobs[i].velX;
this.blobs[i].y += this.blobs[i].velY;
for (var j = 0; j < this.blobs.length; j++) {
if (j != i && this.blobs[i] !== undefined) {
var blob1 = this.blobs[i];
var blob2 = this.blobs[j];
var x = blob2.x - blob1.x; // get the vector from blob1 to blob2
var y = blob2.y - blob1.y; //
var dist = Math.sqrt(x * x + y * y); // get the distance between the two blobs
if (dist < blob1.mass + blob2.mass) { // if the distance is less than the 2 radius
// if there is overlap move blob one along the line between the two the distance of the two radius
x /= dist; // normalize the vector. This makes the vector 1 unit long
y /= dist;
// multiplying the normalised vector by the correct distance between the two
// and subtracting that distance from the blob 2 give the new pos of
// blob 1
blob1.x = blob2.x - x * (blob1.mass + blob2.mass);
blob1.y = blob2.y - y * (blob1.mass + blob2.mass);
}
}
}
}
this.x += (mouseX - width / 2) / (width / 2) * 1;
this.y += (mouseY - height / 2) / (height / 2) * 1
},
split: function(cell) {
cell.mass /= 2;
this.blobs.push({
x: cell.x,
y: cell.y,
mass: cell.mass
});
},
draw: function() {
for (var i = 0; i < this.blobs.length; i++) {
ctx.fillStyle = "red";
ctx.beginPath();
ctx.arc(-camera.x + this.blobs[i].x, -camera.y + this.blobs[i].y, this.blobs[i].mass, 0, Math.PI * 2);
ctx.fill();
ctx.closePath();
}
}
};
function handleMouseMove(e) {
mouseX = e.clientX;
mouseY = e.clientY;
}
function setup() {
canvas = document.getElementById("game");
ctx = canvas.getContext("2d");
canvas.width = width;
canvas.height = height;
addEventListener("mousemove", handleMouseMove);
player.blobs.push({
x: 0,
y: 0,
mass: player.defaultMass
});
player.blobs.push({
x: 100,
y: 100,
mass: player.defaultMass / 2
});
player.blobs.push({
x: 100,
y: 100,
mass: player.defaultMass * 2
});
var loop = function() {
update();
draw();
requestAnimationFrame(loop);
}
requestAnimationFrame(loop);
}
function update() {
camera.update(player.blobs[0]);
player.update();
}
function draw() {
ctx.fillStyle = "#fff";
ctx.fillRect(0, 0, width, height);
player.draw();
}
setup();
body {
margin: 0;
padding: 0;
}
<canvas id="game">kindly update your browser.</canvas>
var
canvas,
ctx,
width = innerWidth,
height = innerHeight,
mouseX = 0,
mouseY = 0;
var
camera = {
x: 0,
y: 0,
update: function(obj) {
this.x = obj.x - width / 2;
this.y = obj.y - height / 2;
}
},
player = {
defaultMass: 54,
x: 0,
y: 0,
blobs: [],
update: function() {
for (var i = 0; i < this.blobs.length; i++) {
var x = mouseX + camera.x - this.blobs[i].x;
var y = mouseY + camera.y - this.blobs[i].y;
var length = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
var speed = 54 / this.blobs[i].mass;
this.blobs[i].velX = x / length * speed * Math.min(1, Math.pow(x / this.blobs[i].mass, 2));
this.blobs[i].velY = y / length * speed * Math.min(1, Math.pow(x / this.blobs[i].mass, 2));
this.blobs[i].x += this.blobs[i].velX;
this.blobs[i].y += this.blobs[i].velY;
for (var j = 0; j < this.blobs.length; j++) {
if (j != i && this.blobs[i] !== undefined) {
var blob1 = this.blobs[i];
var blob2 = this.blobs[j];
var dist = Math.sqrt(Math.pow(blob2.x - blob1.x, 2) + Math.pow(blob2.y - blob1.y, 2));
if (dist < blob1.mass + blob2.mass) {
if (this.blobs[i].x < this.blobs[j].x) {
this.blobs[i].x--;
} else if (this.blobs[i].x > this.blobs[j].x) {
this.blobs[i].x++;
}
if (this.blobs[i].y < this.blobs[j].y) {
this.blobs[i].y--;
} else if ((this.blobs[i].y > this.blobs[j].y)) {
this.blobs[i].y++;
}
}
}
}
}
this.x += (mouseX - width / 2) / (width / 2) * 1;
this.y += (mouseY - height / 2) / (height / 2) * 1
},
split: function(cell) {
cell.mass /= 2;
this.blobs.push({
x: cell.x,
y: cell.y,
mass: cell.mass
});
},
draw: function() {
for (var i = 0; i < this.blobs.length; i++) {
ctx.fillStyle = "red";
ctx.beginPath();
ctx.arc(-camera.x + this.blobs[i].x, -camera.y + this.blobs[i].y, this.blobs[i].mass, 0, Math.PI * 2);
ctx.fill();
ctx.closePath();
}
}
};
function handleMouseMove(e) {
mouseX = e.clientX;
mouseY = e.clientY;
}
function setup() {
canvas = document.getElementById("game");
ctx = canvas.getContext("2d");
canvas.width = width;
canvas.height = height;
addEventListener("mousemove", handleMouseMove);
player.blobs.push({
x: 0,
y: 0,
mass: player.defaultMass
});
player.blobs.push({
x: 100,
y: 100,
mass: player.defaultMass / 2
});
player.blobs.push({
x: 100,
y: 100,
mass: player.defaultMass * 2
});
var loop = function() {
update();
draw();
requestAnimationFrame(loop);
}
requestAnimationFrame(loop);
}
function update() {
camera.update(player.blobs[0]);
player.update();
}
function draw() {
ctx.fillStyle = "#fff";
ctx.fillRect(0, 0, width, height);
player.draw();
}
setup();
body {
margin: 0;
padding: 0;
}
<canvas id="game">kindly update your browser.</canvas>
I've modified this example of inverse kinematics in JavaScript with HTML5 Canvas and made it dynamic by seperating it into a function, and it works, but the example only uses 3 points -- start, middle, and end, and I'd like to change the number of points at will. Here's my current fiddle...
function _kinematics(joints, fx, mouse) {
joints.forEach(function (joint) {
joint.target = joint.target || {
x: fx.canvas.width / 2,
y: fx.canvas.height / 2
};
joint.start = joint.start || {
x: 0,
y: 0
};
joint.middle = joint.middle || {
x: 0,
y: 0
};
joint.end = joint.end || {
x: 0,
y: 0
};
joint.length = joint.length || 50;
});
var theta,
$theta,
_theta,
dx,
dy,
distance;
joints.forEach(function (joint) {
if (mouse) {
joint.target.x = mouse.x;
joint.target.y = mouse.y;
}
dx = joint.target.x - joint.start.x;
dy = joint.target.y - joint.start.y;
distance = Math.sqrt(Math.pow(dx, 2) + Math.pow(dy, 2));
_theta = Math.atan2(dy, dx);
if (distance < joint.length) {
theta = Math.acos(distance / (joint.length + joint.length)) + _theta;
dx = dx - joint.length * Math.cos(theta);
dy = dy - joint.length * Math.sin(theta);
$theta = Math.atan2(dy, dx);
} else {
theta = $theta = _theta;
}
joint.middle.x = joint.start.x + Math.cos(theta) * joint.length;
joint.middle.y = joint.start.y + Math.sin(theta) * joint.length;
joint.end.x = joint.middle.x + Math.cos($theta) * joint.length;
joint.end.y = joint.middle.y + Math.sin($theta) * joint.length;
fx.beginPath();
fx.moveTo(joint.start.x, joint.start.y);
/* for (var i = 0; i < joint.points.length / 2; i++) {
fx.lineTo(joint.points[i].x, joint.points[i].y);
} */
fx.lineTo(joint.middle.x, joint.middle.y);
/* for (var j = joint.points.length / 2; j < joint.points.length; j++) {
fx.lineTo(joint.points[j].x, joint.points[j].y);
} */
fx.lineTo(joint.end.x, joint.end.y);
fx.strokeStyle = "rgba(0,0,0,0.5)";
fx.stroke();
fx.beginPath();
fx.arc(joint.start.x, joint.start.y, 10, 0, Math.PI * 2);
fx.fillStyle = "rgba(255,0,0,0.5)";
fx.fill();
fx.beginPath();
fx.arc(joint.middle.x, joint.middle.y, 10, 0, Math.PI * 2);
fx.fillStyle = "rgba(0,255,0,0.5)";
fx.fill();
fx.beginPath();
fx.arc(joint.end.x, joint.end.y, 10, 0, Math.PI * 2);
fx.fillStyle = "rgba(0,0,255,0.5)";
fx.fill();
});
}
That's just the function, I've omitted the rest for brevity. As you can see, the commented-out lines were my attempt to draw the other points.
Also, here's where I populate the joints array with the points and such. See commented lines.
populate(_joints, $joints, function() {
var coords = randCoords(map);
var o = {
start: {
x: coords.x,
y: coords.y
},
// points: [],
target: {
x: mouse.x,
y: mouse.y
}
};
/* for (var p = 0; p < 10; p++) {
o.points.push({
x: p === 0 ? o.start.x + (o.length || 50) : o.points[p - 1].x + (o.length || 50),
y: p === 0 ? o.start.y + (o.length || 50) : o.points[p - 1].y + (o.length || 50)
});
}; */
return o;
});
How would I make this function work with n points?
I visited the Stack Exchange Winter Bash website and I love the falling snow! My question is, how can I recreate a similar effect that looks as nice. I attempted to reverse engineer the code to see if I could figure it out but alas no luck there. The JS is over my head. I did a bit of googling and came across some examples but they were not as elegant as the SE site or did not look very good.
Can anyone provide some instructions on how to replicate what the SE Winter Bash site creates or a place where I might learn how to do this?
Edit: I would like to replicate the effect as close as possible, IE: falling snow with snowflakes, and being able to move the mouse and cause the snow to move or swirl with the mouse moments.
Great question, I actually wrote a snow plugin a while ago that I continually update see it in action. Also a link to the pure js source
I noticed you tagged the question html5 and canvas, however you can do it without using either, and just standard elements with images or different background colors.
Here's two really simple ones I put together just now for you to mess with. The key in my opinion is using sin to get the nice wavy effect as the flakes fall. The first one uses the canvas element, the 2nd one uses regular dom elements.
Since I'm absolutely addicted to canvas here's a canvas version that performs quite nicely in my opinion.
Canvas version
Full Screen
(function() {
var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame ||
function(callback) {
window.setTimeout(callback, 1000 / 60);
};
window.requestAnimationFrame = requestAnimationFrame;
})();
var flakes = [],
canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d"),
flakeCount = 200,
mX = -100,
mY = -100
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
function snow() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < flakeCount; i++) {
var flake = flakes[i],
x = mX,
y = mY,
minDist = 150,
x2 = flake.x,
y2 = flake.y;
var dist = Math.sqrt((x2 - x) * (x2 - x) + (y2 - y) * (y2 - y)),
dx = x2 - x,
dy = y2 - y;
if (dist < minDist) {
var force = minDist / (dist * dist),
xcomp = (x - x2) / dist,
ycomp = (y - y2) / dist,
deltaV = force / 2;
flake.velX -= deltaV * xcomp;
flake.velY -= deltaV * ycomp;
} else {
flake.velX *= .98;
if (flake.velY <= flake.speed) {
flake.velY = flake.speed
}
flake.velX += Math.cos(flake.step += .05) * flake.stepSize;
}
ctx.fillStyle = "rgba(255,255,255," + flake.opacity + ")";
flake.y += flake.velY;
flake.x += flake.velX;
if (flake.y >= canvas.height || flake.y <= 0) {
reset(flake);
}
if (flake.x >= canvas.width || flake.x <= 0) {
reset(flake);
}
ctx.beginPath();
ctx.arc(flake.x, flake.y, flake.size, 0, Math.PI * 2);
ctx.fill();
}
requestAnimationFrame(snow);
};
function reset(flake) {
flake.x = Math.floor(Math.random() * canvas.width);
flake.y = 0;
flake.size = (Math.random() * 3) + 2;
flake.speed = (Math.random() * 1) + 0.5;
flake.velY = flake.speed;
flake.velX = 0;
flake.opacity = (Math.random() * 0.5) + 0.3;
}
function init() {
for (var i = 0; i < flakeCount; i++) {
var x = Math.floor(Math.random() * canvas.width),
y = Math.floor(Math.random() * canvas.height),
size = (Math.random() * 3) + 2,
speed = (Math.random() * 1) + 0.5,
opacity = (Math.random() * 0.5) + 0.3;
flakes.push({
speed: speed,
velY: speed,
velX: 0,
x: x,
y: y,
size: size,
stepSize: (Math.random()) / 30,
step: 0,
angle: 180,
opacity: opacity
});
}
snow();
};
canvas.addEventListener("mousemove", function(e) {
mX = e.clientX,
mY = e.clientY
});
init();
Standard element version
var flakes = [],
bodyHeight = getDocHeight(),
bodyWidth = document.body.offsetWidth;
function snow() {
for (var i = 0; i < 50; i++) {
var flake = flakes[i];
flake.y += flake.velY;
if (flake.y > bodyHeight - (flake.size + 6)) {
flake.y = 0;
}
flake.el.style.top = flake.y + 'px';
flake.el.style.left = ~~flake.x + 'px';
flake.step += flake.stepSize;
flake.velX = Math.cos(flake.step);
flake.x += flake.velX;
if (flake.x > bodyWidth - 40 || flake.x < 30) {
flake.y = 0;
}
}
setTimeout(snow, 10);
};
function init() {
var docFrag = document.createDocumentFragment();
for (var i = 0; i < 50; i++) {
var flake = document.createElement("div"),
x = Math.floor(Math.random() * bodyWidth),
y = Math.floor(Math.random() * bodyHeight),
size = (Math.random() * 5) + 2,
speed = (Math.random() * 1) + 0.5;
flake.style.width = size + 'px';
flake.style.height = size + 'px';
flake.style.background = "#fff";
flake.style.left = x + 'px';
flake.style.top = y;
flake.classList.add("flake");
flakes.push({
el: flake,
speed: speed,
velY: speed,
velX: 0,
x: x,
y: y,
size: 2,
stepSize: (Math.random() * 5) / 100,
step: 0
});
docFrag.appendChild(flake);
}
document.body.appendChild(docFrag);
snow();
};
document.addEventListener("mousemove", function(e) {
var x = e.clientX,
y = e.clientY,
minDist = 150;
for (var i = 0; i < flakes.length; i++) {
var x2 = flakes[i].x,
y2 = flakes[i].y;
var dist = Math.sqrt((x2 - x) * (x2 - x) + (y2 - y) * (y2 - y));
if (dist < minDist) {
rad = Math.atan2(y2, x2), angle = rad / Math.PI * 180;
flakes[i].velX = (x2 / dist) * 0.2;
flakes[i].velY = (y2 / dist) * 0.2;
flakes[i].x += flakes[i].velX;
flakes[i].y += flakes[i].velY;
} else {
flakes[i].velY *= 0.9;
flakes[i].velX
if (flakes[i].velY <= flakes[i].speed) {
flakes[i].velY = flakes[i].speed;
}
}
}
});
init();
function getDocHeight() {
return Math.max(
Math.max(document.body.scrollHeight, document.documentElement.scrollHeight), Math.max(document.body.offsetHeight, document.documentElement.offsetHeight), Math.max(document.body.clientHeight, document.documentElement.clientHeight));
}
I've created a pure HTML 5 and js snowfall.
Check it out on my code pen here: https://codepen.io/onlintool24/pen/GRMOBVo
// Amount of Snowflakes
var snowMax = 35;
// Snowflake Colours
var snowColor = ["#DDD", "#EEE"];
// Snow Entity
var snowEntity = "•";
// Falling Velocity
var snowSpeed = 0.75;
// Minimum Flake Size
var snowMinSize = 8;
// Maximum Flake Size
var snowMaxSize = 24;
// Refresh Rate (in milliseconds)
var snowRefresh = 50;
// Additional Styles
var snowStyles = "cursor: default; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; -o-user-select: none; user-select: none;";
/*
// End of Configuration
// ----------------------------------------
// Do not modify the code below this line
*/
var snow = [],
pos = [],
coords = [],
lefr = [],
marginBottom,
marginRight;
function randomise(range) {
rand = Math.floor(range * Math.random());
return rand;
}
function initSnow() {
var snowSize = snowMaxSize - snowMinSize;
marginBottom = document.body.scrollHeight - 5;
marginRight = document.body.clientWidth - 15;
for (i = 0; i <= snowMax; i++) {
coords[i] = 0;
lefr[i] = Math.random() * 15;
pos[i] = 0.03 + Math.random() / 10;
snow[i] = document.getElementById("flake" + i);
snow[i].style.fontFamily = "inherit";
snow[i].size = randomise(snowSize) + snowMinSize;
snow[i].style.fontSize = snow[i].size + "px";
snow[i].style.color = snowColor[randomise(snowColor.length)];
snow[i].style.zIndex = 1000;
snow[i].sink = snowSpeed * snow[i].size / 5;
snow[i].posX = randomise(marginRight - snow[i].size);
snow[i].posY = randomise(2 * marginBottom - marginBottom - 2 * snow[i].size);
snow[i].style.left = snow[i].posX + "px";
snow[i].style.top = snow[i].posY + "px";
}
moveSnow();
}
function resize() {
marginBottom = document.body.scrollHeight - 5;
marginRight = document.body.clientWidth - 15;
}
function moveSnow() {
for (i = 0; i <= snowMax; i++) {
coords[i] += pos[i];
snow[i].posY += snow[i].sink;
snow[i].style.left = snow[i].posX + lefr[i] * Math.sin(coords[i]) + "px";
snow[i].style.top = snow[i].posY + "px";
if (snow[i].posY >= marginBottom - 2 * snow[i].size || parseInt(snow[i].style.left) > (marginRight - 3 * lefr[i])) {
snow[i].posX = randomise(marginRight - snow[i].size);
snow[i].posY = 0;
}
}
setTimeout("moveSnow()", snowRefresh);
}
for (i = 0; i <= snowMax; i++) {
document.write("<span id='flake" + i + "' style='" + snowStyles + "position:absolute;top:-" + snowMaxSize + "'>" + snowEntity + "</span>");
}
window.addEventListener('resize', resize);
window.addEventListener('load', initSnow);
body{
background: skyblue;
height:100%;
width:100%;
display:block;
position:relative;
}
<span id="flake0" style="cursor: default; user-select: none; position: absolute; font-family: inherit; font-size: 19px; color: rgb(221, 221, 221); z-index: 1000; left: 226px; top: 561px;">•</span>
The falling snow is simple: Create a canvas, create a bunch of snowflakes, draw them.
You can create a snowflake class like so:
function Snowflake() {
this.x = Math.random()*canvas.width;
this.y = -16;
this.speed = Math.random()*3+1;
this.direction = Math.random()*360;
this.maxSpeed = 4;
}
Or something like that. Then you have a timer that, each step, adjusts each snowflake's direction by a small amount, and then calculates its new X and Y by factoring in the Speed and Direction.
It's hard to explain, but actually quite basic.