JSFiddle - React, Tailwind, and code Playground

by blparker

HTML

<canvas id='canvas' width='300' height='300'></canvas>

<button onclick='clear()'>Clear</div>

CSS

canvas { background:whitesmoke}
div { width:100px; height:100px; margin-top:100px; border:1px solid black }

JavaScript

// Bind canvas to listeners
var canvas = document.getElementById('canvas');
canvas.addEventListener('mousedown', mouseDown, false);
canvas.addEventListener('mousemove', mouseMove, false);
canvas.addEventListener('mouseup', mouseUp, false);
var ctx = canvas.getContext('2d');

ctx.lineWidth = 5;
ctx.lineJoin = 'round';
ctx.lineCap = 'round';

var started = false;
var lastx = 0;
var lasty = 0;

// create an in-memory canvas
var memCanvas = document.createElement('canvas');
memCanvas.width = 300;
memCanvas.height = 300;
var memCtx = memCanvas.getContext('2d');
var points = [];

function mouseDown(e) {
    var m = getMouse(e, canvas);
    points.push({
        x: m.x,
        y: m.y
    });
    started = true;
};

function mouseMove(e) { 
        if (started) {
            ctx.clearRect(0, 0, 300, 300);
            // put back the saved content
            ctx.drawImage(memCanvas, 0, 0);
            var m = getMouse(e, canvas);
            points.push({
                x: m.x,
                y: m.y
            });
            drawPoints(ctx, points);
        }
    };

function mouseUp(e) { 
    if (started) {
        started = false;
        // When the pen is done, save the resulting context
        // to the in-memory canvas
        memCtx.clearRect(0, 0, 300, 300);
        memCtx.drawImage(canvas, 0, 0);
        points = [];
    }
};

// clear both canvases!
function clear() {
    context.clearRect(0, 0, 300, 300);
    memCtx.clearRect(0, 0, 300, 300);
};




function drawPoints(ctx, points) {
    // draw a basic circle instead
    if (points.length < 6) {
        var b = points[0];
        ctx.beginPath(), 
        ctx.arc(b.x, b.y, ctx.lineWidth / 2, 0, Math.PI * 2, !0), 
        ctx.closePath(), ctx.fill();
        return
    }
    
    ctx.beginPath(),
    ctx.moveTo(points[0].x, points[0].y);

    // draw a bunch of quadratics, using the average of two points as the control point
    for (i = 1; i < points.length - 2; i++) {
        var c = (points[i].x +...