一起动手实现 canvas 元素创建,绑定事件,以及销毁😊

1,724 阅读1分钟
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>A Great Demo on CodePen</title>
    <style>
        canvas {
            position: absolute;
            left: 0;
            top: 0;
            right: 0;
            bottom: 0;
            margin: auto;
            border: 1px solid #999;
        }
    </style>
</head>

<body>
    <canvas></canvas>
    <script>
        const canvas = document.querySelector("canvas");
        const ctx = canvas.getContext("2d");
        const colorList = {};
        canvas.addEventListener("click", (e) => {
            let { offsetX, offsetY } = e;
            colorList[
                ctx.getImageData(offsetX, offsetY, 1, 1).data.slice(0, 3).join("")
            ]?.();
        });

        class Player {
            constructor(obj) {
                this.obj = obj
                colorList[obj.rgb.join("")] = obj.click;
                ctx.fillStyle = `rgb(${obj.rgb[0]}, ${obj.rgb[1]}, ${obj.rgb[2]})`;
                ctx.fillRect(obj.x, obj.y, obj.width, obj.height);
            }
            clear() {
                ctx.clearRect(this.obj.x, this.obj.y, this.obj.width, this.obj.height)
                delete colorList[this.obj.rgb.join('')]
            }
        }

        const player1 = new Player({
            rgb: [200, 100, 100],
            x: 10,
            y: 10,
            width: 100,
            height: 100,
            click: () => {
                const player2 = new Player({
                    rgb: [100, 100, 100],
                    x: 120,
                    y: 10,
                    width: 100,
                    height: 100,
                    click: () => {
                        player1.clear()
                    }
                });
            }
        });
    </script>
</body>

</html>

代码有不足之处,只是体现一种思想 😄