JSFiddle - React, Tailwind, and code Playground

by gamealchemist

HTML

<canvas id="canvas" width=500 height=300></canvas>
<br/>
<button onclick="clipCircleExample();">Clip straight circle</button>
<br/>
<button onclick="clipRevertCircleExample();">Clip Reverse circle</button>
<br/>
<button onclick="clipTriangleExample();">Clip straight triangle</button>
<br/>
<button onclick="clipRevertTriangleExample();">Clip Reverse triangle</button>
<br/>
<button onclick="clipBothExample();">Clip straight both</button>
<br/>
<button onclick="clipRevertBothExample();">Clip Reverse both</button>

JavaScript

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

var img = new Image();
img.onload = function () {

    // clips the canvas with provided path function
    // if pathFunction is an array, clips with all functions
    function clip(pathFunction) {
        ctx.beginPath();
        if (Array.isArray(pathFunction)) pathFunction.forEach(execute);
        else pathFunction();
        ctx.clip();
    }

    // clips the canvas with the invert of provided path function
    // if pathFunction is an array, remove clips defined by all functions
    function clipRevert(pathFunction) {
        ctx.beginPath();
        ctx.rect(0, 0, canvas.width, ctx.canvas.height);
        if (Array.isArray(pathFunction)) pathFunction.forEach(execute);
        else pathFunction();
        ctx.clip();
    }

    function execute(fn) {
        return fn();
    }

    function circlePath(x, y, r) {
        ctx.moveTo(x, y, x + r);
        ctx.arc(x, y, r, 0, Math.PI * 2, true);
        ctx.closePath();
    }

    function trianglePath() {
        ctx.moveTo(80, 100);
        ctx.lineTo(50, 150)
        ctx.lineTo(110, 150);
        ctx.lineTo(80, 100);
    }

    function clipExample(reverted) {
        var clipFunctions = Array.prototype.slice.call(arguments, 1);
        ctx.save();
        ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
        if (reverted) clipRevert(clipFunctions);
        else clip(clipFunctions);
        ctx.drawImage(img, 0, 0);
        ctx.restore();
    }

    window.clipCircleExample = function () {
        clipExample(false, circlePath.bind(null, 220, 180, 100));
    }

    window.clipRevertCircleExample = function () {
        clipExample(true, circlePath.bind(null, 220, 180, 100));
    }

    window.clipRevertTriangleExample = function () {
        clipExample(true, trianglePath);
    }

    window.clipTriangleExample = function () {
        clipExample(false, trianglePath);
    }

    window.clipRevertBothExample =...