Skip to content

Instantly share code, notes, and snippets.

@wuriyanto48
Last active June 26, 2024 17:04
Show Gist options
  • Save wuriyanto48/13ae479c02c5533802368931c874724b to your computer and use it in GitHub Desktop.
Save wuriyanto48/13ae479c02c5533802368931c874724b to your computer and use it in GitHub Desktop.
Bezier Curves in Javascript
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<canvas id="myCanvas" width="800" height="400" style="border:1px solid #000000;">
Your browser does not support the HTML canvas tag.
</canvas>
<input type="range" min="1" max="100" value="1" class="slider" id="tval">
<script>
function draw() {
var tval = document.getElementById("tval");
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var p1 = {x: 70, y: 200};
var p2 = {x: 200, y: 50};
var p3 = {x: 200, y: 300};
function addPoint(p1, p2) {
return {x: p1.x+p2.x, y: p1.y+p2.y};
}
function subPoint(p1, p2) {
return {x: p1.x-p2.x, y: p1.y-p2.y};
}
function lerp(p1, p2, t) {
// t = time or percentage how far between p1 and p2
var lx = (1 - t) * p1.x + t * p2.x;
var ly = (1 - t) * p1.y + t * p2.y;
return {x: lx, y: ly};
}
ctx.fillStyle = "black";
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.moveTo(p1.x, p1.y);
ctx.lineTo(p2.x, p2.y);
ctx.lineTo(p3.x, p3.y);
ctx.strokeStyle = "red";
ctx.stroke();
tval.addEventListener("change", function() {
var t = tval.value / 100;
var l1 = lerp(p1, p2, t);
var l2 = lerp(p2, p3, t);
var q1 = lerp(l1, l2, t);
ctx.fillStyle = "red";
ctx.fillRect(q1.x, q1.y, 10, 10);
console.log(q1);
}, false);
}
window.requestAnimationFrame(draw);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment