javascript 在页面上创建绘图画布

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript 在页面上创建绘图画布相关的知识,希望对你有一定的参考价值。

(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;
                }
            };
        }
    };
})();

以上是关于javascript 在页面上创建绘图画布的主要内容,如果未能解决你的问题,请参考以下文章

Javascript 如何在移动设备上画布绘图工作

可拖动图像上的画布绘图

在 HTML5 画布上工作时出现 JavaScript (JQuery) 问题

用html5的canvas和JavaScript创建一个绘图程序

CSS绘图和数据存储原理

在“动态”画布上绘图