From 7c06d07bb086ba9aaf0dedd8b138e8605980704c Mon Sep 17 00:00:00 2001 From: Thibaud Date: Fri, 27 Sep 2024 17:57:08 +0200 Subject: [PATCH] enable to add new points on spline --- common.js | 12 ++++++++++++ index.html | 1 + spline.js | 37 ++++++++++++++++++++++++++++++------- 3 files changed, 43 insertions(+), 7 deletions(-) diff --git a/common.js b/common.js index 13cfd37..5fb801c 100644 --- a/common.js +++ b/common.js @@ -5,6 +5,18 @@ export function lerp(a, b, p) { }; } +export function quadraticBezier(a, b, c, res=0.05) { + const eps = 0.001; // to prevent issues with float comparaison (p <= 1) + const curve = []; + for (let p = 0; p - 1 < eps; p += res) { + const ab = lerp(a, b, p); + const bc = lerp(b, c, p); + const abc = lerp(ab, bc, p); + curve.push(abc); + } + return curve; +} + export function cubicBezier(a, b, c, d, res=0.05) { const eps = 0.001; // to prevent issues with float comparaison (p <= 1) const curve = []; diff --git a/index.html b/index.html index 1ccc603..fc929dd 100644 --- a/index.html +++ b/index.html @@ -18,6 +18,7 @@
  • Grid
  • Bezier demo #1
  • Bezier demo #2
  • +
  • Bezier spline demo
  • diff --git a/spline.js b/spline.js index 95ae105..5e4b51c 100644 --- a/spline.js +++ b/spline.js @@ -1,4 +1,4 @@ -import { resizeCanvas, drawCircle, drawLine, cubicBezier } from "./common.js" +import { resizeCanvas, drawCircle, drawLine, cubicBezier, quadraticBezier } from "./common.js" function drawPoints(ctx, points) { for (const p of points) { @@ -14,12 +14,21 @@ function drawCurve(ctx, curve) { } function draw(ctx, points) { - const bezier1 = cubicBezier(...points.slice(0, 4)); - drawCurve(ctx, bezier1); - - const bezier2 = cubicBezier(...points.slice(3, 7)); - drawCurve(ctx, bezier2); - + let start = 0; + while (true) { + const sl = points.slice(start, start + 4); + if (sl.length === 4) { + const bezier = cubicBezier(...sl); + drawCurve(ctx, bezier); + start += 3; + } else if (sl.length === 3) { + const bezier = quadraticBezier(...sl); + drawCurve(ctx, bezier); + start += 2; + } else { + break; + } + } drawPoints(ctx, points); } @@ -41,6 +50,13 @@ function init() { resizeCanvas(ctx); // Init canvas draw(ctx, points); + canvas.oncontextmenu = (evt) => { + evt.preventDefault(); + points = []; + // redraw + ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height); + draw(ctx, points); + }; canvas.onmousedown = (evt) => { const { clientX, clientY } = evt; for (const p of points) { @@ -48,6 +64,13 @@ function init() { selection = points.indexOf(p); } } + if (selection === undefined) { + points.push({ x: clientX, y: clientY }); + // redraw + ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height); + draw(ctx, points); + + } }; canvas.onmousemove = (evt) => {