JSFiddle - React, Tailwind, and code Playground

by m1erickson

HTML

<p>Drag mouse to create quadratic bezier</p>
<p>that goes through the mouse position</p>
<p>The 3rd dot is the calculated control point</p>
<canvas id="canvas" width=400 height=400></canvas>

CSS

body{ background-color: ivory; padding:10px; }
canvas{border:1px solid red;}

JavaScript

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

// get the position of the canvas
// relative to the window
var canvasOffset = $("#canvas").offset();
var offsetX = canvasOffset.left;
var offsetY = canvasOffset.top;

// set the start and end points
var startX = 25;
var startY = 50;
var endX = 275;
var endY = 200;
// some vars for the mouse position
var mouseX;
var mouseY;
var isDragging = false;

// set curve color and stroke-width
ctx.strokeStyle = "blue"
ctx.fillStyle = "red"
ctx.lineWidth = 5;

// draw the startpoint, endpoint and line
// just to get the user some reference points
ctx.beginPath();
ctx.moveTo(startX, startY);
ctx.lineTo(endX, endY);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(startX, startY);
ctx.arc(startX, startY, 10, 0, 2 * Math.PI, false);
ctx.moveTo(endX, endY);
ctx.arc(endX, endY, 10, 0, 2 * Math.PI, false);
ctx.fill();


// when the user drags the mouse draw a quad-curve
// between the 2 points and the mouse position
function handleMouseMove(e) {
    mouseX = parseInt(e.clientX - offsetX);
    mouseY = parseInt(e.clientY - offsetY);

    // calc a control point
    var cpX = 2 * mouseX - startX / 2 - endX / 2;
    var cpY = 2 * mouseY - startY / 2 - endY / 2;

    ctx.clearRect(0, 0, canvas.width, canvas.height);

    // draw a quad-curve
    ctx.beginPath();
    ctx.moveTo(startX, startY);
    ctx.quadraticCurveTo(cpX, cpY, endX, endY);
    ctx.stroke();

    // draw the Start, End and Control points
    ctx.beginPath();
    ctx.moveTo(startX, startY);
    ctx.arc(startX, startY, 10, 0, 2 * Math.PI, false);
    ctx.moveTo(cpX, cpY);
    ctx.arc(cpX, cpY, 10, 0, 2 * Math.PI, false);
    ctx.moveTo(endX, endY);
    ctx.arc(endX, endY, 10, 0, 2 * Math.PI, false);
    ctx.fillStyle = "red";
    ctx.fill();
    ctx.beginPath();
    ctx.fillStyle = "gold";
    ctx.arc(cpX, cpY, 10, 0, 2 * Math.PI, false);
    ctx.fill();
}

$("#canvas").mousedown(function (e) {
    isDragging =...