JSFiddle - React, Tailwind, and code Playground

by m1erickson

HTML

<h4>drag the mouse quickly to draw disappearing line.</h4>
<canvas id="canvas" width=300 height=300></canvas>

CSS

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

JavaScript

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.lineCap = "round";
ctx.lineJoin = "round";
ctx.lineWidth = 4;
ctx.strokeStyle = "blue";

var $canvas = $("#canvas");
var canvasOffset = $canvas.offset();
var offsetX = canvasOffset.left;
var offsetY = canvasOffset.top;
var scrollX = $canvas.scrollLeft();
var scrollY = $canvas.scrollTop();

var isDown = false;
var startX;
var startY;

var points = [];
var s = 0;
animate();

function drawLatestLines() {
    s += 0.50;
    var ss = parseInt(s);
    if (s > points.length - 2) {
        return;
    }
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.beginPath();
    ctx.moveTo(points[ss].x, points[ss].y);
    for (var i = ss; i < points.length; i++) {
        ctx.lineTo(points[i].x, points[i].y);
    }
    ctx.stroke();
}

function animate() {
    requestAnimationFrame(animate);
    drawLatestLines();
}

function handleMouseDown(e) {
    e.preventDefault();
    e.stopPropagation();

    startX = parseInt(e.clientX - offsetX);
    startY = parseInt(e.clientY - offsetY);

    // Put your mousedown stuff here
    points.length = 0;
    points.push({
        x: startX,
        y: startY
    });
    s = 0;
    isDown = true;

}

function handleMouseUp(e) {
    e.preventDefault();
    e.stopPropagation();

    mouseX = parseInt(e.clientX - offsetX);
    mouseY = parseInt(e.clientY - offsetY);

    // Put your mouseup stuff here
    isDown = false;
}

function handleMouseOut(e) {
    e.preventDefault();
    e.stopPropagation();

    mouseX = parseInt(e.clientX - offsetX);
    mouseY = parseInt(e.clientY - offsetY);

    // Put your mouseOut stuff here
    isDown = false;
}

function handleMouseMove(e) {
    if (!isDown) {
        return;
    }
    e.preventDefault();
    e.stopPropagation();

    mouseX = parseInt(e.clientX - offsetX);
    mouseY = parseInt(e.clientY - offsetY);

    points.push({
        x: mouseX,
        y: mouseY
    });

}

$("#canvas").mousedown(function...