JSFiddle - React, Tailwind, and code Playground

by m1erickson

HTML

<p>Click to move the ball group to a new location</p>
<p>WITHOUT recalculating each new ball position!</p>
<br/>
<canvas id="canvas" width=350 height=300></canvas>

CSS

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

JavaScript

var canvas = document.getElementById("canvas");
        var ctx = canvas.getContext("2d");
        var canvasOffset = $("#canvas").offset();
        var offsetX = canvasOffset.left;
        var offsetY = canvasOffset.top;

        drawBallGroup();

        function drawBallGroup() {
            drawBall(8, 10, 5, "red");
            drawBall(20, 15, 10, "green");
            drawBall(25, 25, 8, "blue");
            drawBall(5, 22, 10, "orange");
            drawBall(18, 30, 10, "black");
        }

        function drawBall(x, y, radius, color) {
            ctx.beginPath();
            ctx.fillStyle = color;
            ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
            ctx.fill();
        }


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

            // clear the canvas
            ctx.clearRect(0, 0, canvas.width, canvas.height);

            // do a translate to mouseX,mouseY
            // all draws will be now be done RELATIVE to mouseX,mouseY
            // so if we ctx.translate(100,100)
            // then ctx.rect(0,0,10,10) will actually be drawn at 100,100
            ctx.translate(mouseX, mouseY);

            // draw the ball group
            // notice we didn't have to calculate ANY new positions!!
            drawBallGroup();

            // translate back after we're done
            ctx.translate(-mouseX, -mouseY);
        }

        $("#canvas").mousedown(function (e) {
            handleMouseDown(e);
        });