Reputation: 1593
I want to create a parabola using the library Two.js. Here is the code that I am using:
// Create a Two.js instance
var two = new Two({
width: 300,
height: 300
}).appendTo(document.getElementById("parabola"));
var path = two.makePath(0, two.height / 2);
path.stroke = "#000";
path.linewidth = 3;
for (var i = 0; i < two.width; i++) {
var x = i;
var y = Math.pow((x - two.width / 2), 2) / (2 * 50) + two.height / 2;
console.log(`x: ${x} and y: ${y}`);
path.vertices.push(new Two.Vector(x, y));
}
two.update();
<script src="https://cdnjs.cloudflare.com/ajax/libs/two.js/0.8.10/two.min.js"></script>
<div id="parabola"></div>
I should draw a parabola that starts at the left end and branches out at the right end. However, the result I get is just two lines.
Am I doing something wrong mathematically or failing to close the path somehow?
Upvotes: 0
Views: 121
Reputation: 48620
You did not close your path.
Also, your y
calculation is drawing the image too low, and your starting y
is in the middle.
Tip: Try creating a function that returns the y
coordinate for a given x
.
// Create a Two.js instance
const two = new Two({ width: 300, height: 300 })
.appendTo(document.getElementById("parabola"));
const
xOffset = two.width / 2,
yOffset = two.height / 2;
const path = two.makePath(0, yOffset);
path.fill = 'red';
path.stroke = "#000";
path.linewidth = 3;
const getY = (x) => (x - xOffset)**2 / yOffset - yOffset;
for (let x = 0; x < two.width; x++) {
let y = getY(x);
console.log(`x: ${x} and y: ${y}`);
path.vertices.push(new Two.Vector(x, y));
}
// Connect the last vertex to the first to close the path...
path.vertices.push(new Two.Vector(0, getY(0)));
two.update();
#parabola {
background: lightgrey;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/two.js/0.8.10/two.min.js"></script>
<div id="parabola"></div>
Upvotes: 1