test-canvas/bezier-2.js

65 lines
1.7 KiB
JavaScript
Raw Normal View History

2024-09-27 10:53:05 +00:00
import { resizeCanvas, drawCircle, drawLine, cubicBezier } from "./common.js";
function drawPoints(ctx, points) {
const [a, b, c, d] = points;
drawLine(ctx, a, b, 0xFF00FF);
drawLine(ctx, c, d, 0xFF00FF);
for (const p of points) {
drawCircle(ctx, p, 2, 0xFF00FF);
}
}
function drawCurve(ctx, curve) {
for (let i=0; i < curve.length - 1; ++i) {
drawLine(ctx, curve[i], curve[i+1], 0xFFFFFF);
}
}
2024-09-26 20:46:28 +00:00
function init() {
const canvas = document.getElementById("canvas");
2024-09-27 10:53:05 +00:00
let selection = undefined;
let points = [
{ x: 227, y: 434 },
{ x: 341, y: 234 },
{ x: 649, y: 255 },
{ x: 765, y: 450 },
];
2024-09-26 20:46:28 +00:00
if (canvas.getContext) {
const ctx = canvas.getContext("2d");
2024-09-27 10:53:05 +00:00
resizeCanvas(ctx); // Init canvas
drawPoints(ctx, points);
const bezier = cubicBezier(...points);
drawCurve(ctx, bezier);
canvas.onmousedown = (evt) => {
const { clientX, clientY } = evt;
for (const p of points) {
if (Math.abs(p.x - clientX) < 10 && Math.abs(p.y - clientY) < 10) {
selection = points.indexOf(p);
2024-09-26 20:46:28 +00:00
}
}
2024-09-27 10:53:05 +00:00
};
canvas.onmousemove = (evt) => {
if (selection !== undefined) {
points[selection].x = evt.clientX;
points[selection].y = evt.clientY;
// redraw
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
const bezier = cubicBezier(...points);
drawCurve(ctx, bezier);
drawPoints(ctx, points);
}
};
2024-09-26 20:46:28 +00:00
2024-09-27 10:53:05 +00:00
canvas.onmouseup = () => {
selection = undefined;
};
2024-09-26 20:46:28 +00:00
}
}
init();