g43riko / Drawable canvas

// ==UserScript==
// @name         Drawable canvas
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @include *
// @copyright 2018, g43riko (https://openuserjs.org/users/g43riko)
// @license MIT
// ==/UserScript==


(function(){
    const ACTIVATION_KEY = 87; // W
    const ACTIVATION_BUTTON = 0; // LEFT

    const canvas = document.createElement("canvas");
    const ctx = canvas.getContext("2d");

    canvas.width = window.innerWidth;
    canvas.height = (document.height !== undefined) ? document.height : document.body.offsetHeight;
    canvas.style.position = "absolute";
    canvas.style.top = canvas.style.left = 0;
    canvas.style.zIndex = 10000;
    canvas.style.pointerEvents = "none";
    document.body.appendChild(canvas);

    let isKeyDown = false;
    let isButtonDown = false;

    window.onkeydown = (e) => {
        if (e.keyCode === ACTIVATION_KEY && !isKeyDown) {
            isKeyDown = true;
            const oldOnKeyUp = window.onkeyup;
            const oldOnMouseLeave = window.onmouseleave;
            const oldOnMouseDown = window.onmousedown;

            window.onmousedown = (ee) => {
                if (ee.button === ACTIVATION_BUTTON && !isButtonDown) {
                    const oldOnMouseMove = window.onmousemove;
                    const oldOnMouseUp = window.onmouseup;

                    canvas.style.pointerEvents = "auto";
                    isButtonDown = true;

                    window.onmousemove = (eee) => {
                        ctx.beginPath();
                        ctx.moveTo(eee.pageX - eee.movementX, eee.pageY - eee.movementY);
                        ctx.lineTo(eee.pageX, eee.pageY);
                        ctx.stroke();
                    };
                    window.onmouseup = (eee) => {
                        if (eee.button === ACTIVATION_BUTTON) {
                            window.onmousemove = oldOnMouseMove;
                            window.onmouseup = oldOnMouseUp;
                            isButtonDown = false;
                        }
                    };
                }
            };
            window.onmouseleave = window.onkeyup = (ee) => {
                if (ee.keyCode === ACTIVATION_KEY) {
                    canvas.style.pointerEvents = "none";
                    window.onmouseleave = oldOnMouseLeave;
                    window.onmousedown = oldOnMouseDown;
                    window.onkeyup = oldOnKeyUp;
                    isKeyDown = false;
                }
            };
        }
    };
})();