[js] Custom events and event simulation


Preface

1. Use of custom events
2. Use of event simulation


1. Custom events

1. There are three ways to customize events in js

  • new CustomEvent(‘wheelup’, {});
  • new Event(‘wheelup’, {})
  • document.createEvent('HTMLEvents'); initEvent('wheelup', false, false)
    The third method must be initialized
// 以实现监听鼠标滚轮上滚或者下滚动事件为例子
// 1、自定义事件实现滚轮上下滚动事件
            // 第一种
            // let wheelupEvent = new CustomEvent('wheelup', {});
            // let wheeldownEvent = new CustomEvent('wheeldown', {});

            // 第二种
            // let wheelupEvent = new Event('wheelup', {});
            // let wheeldownEvent = new Event('wheeldown', {});

            // 第三种 这种必须初始化 一般用于编程模拟鼠标等已有事件
            // createEvent参数 HTMLEvents MouseEvents UIEvents
            let wheelupEvent = document.createEvent('HTMLEvents');
            let wheeldownEvent =  document.createEvent('HTMLEvents');
            wheelupEvent.initEvent('wheelup', false, false);
            wheeldownEvent.initEvent('wheeldown', false, false);

            let preY = null;
            window.onwheel = function(e) {
    
    
                // console.log('onwheel11:', e);
                if (e.wheelDelta > 0) {
    
    
                    console.log('onwheelup:')
                    window.dispatchEvent(wheelupEvent, {
    
    data: e.wheelDelta});
                } else {
    
    
                    console.log('onwheeldown:')
                    window.dispatchEvent(wheeldownEvent, {
    
    data: e.wheelDelta});
                };
            }

            window.addEventListener('wheelup', function(e) {
    
    
                alert('wheelupEvent 触发', e);
            })
            window.addEventListener('wheeldown', function(e) {
    
    
                alert('wheeldownEvent 触发', e);
            })

2、createEvent()

1. The createEvent() method returns the newly created Event object and supports one parameter indicating the event type. See the following table for details: 2. The
Insert image description here
initEvent() method is used to initialize the value of the Event created through the DocumentEvent interface.
Supports three parameters: initEvent(eventName, canBubble, preventDefault)
respectively means:

  • event name
  • Is it possible to bubble
  • Whether to block the default action of the event

2. Event Simulation

1. Event simulation is usually used to be compatible with the effects of WAP side and PC side.

Take the canvas drawing board effect on the WAP side that is compatible with the PC side as an example:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>事件模拟</title>
    <style>
        * {
      
      
            margin: 0;
            padding: 0;
        }
        #canvas_box {
      
      
            position: relative;
            width: 100vw;
            height: 100vh;
        }
    </style>
</head>
<body>
    <!-- <div style="height: 2000px;width: 100%;background-color: gray;"></div> -->
    <div id="canvas_box">
        <canvas id="canvas"></canvas>
    </div>
    <button id="btn">下载</button>
</body>
</html>
// 2、通过事件模拟处理移动端的canvas场景
            const canvasEle = document.querySelector('#canvas');
            if (canvasEle.getContext) {
    
    
                let ctx = canvasEle.getContext('2d');
                let container =  document.querySelector('#canvas_box');
                canvasEle.width = container.clientWidth;
                canvasEle.height = container.clientHeight;
                let startPoint = null;
                let movePoint = null;
                let drawFlag = false;
                function draw() {
    
    
                    ctx.lineWidth = 1;
                    ctx.lineCap = 'round';
                    ctx.lineJoin = 'round';
                    ctx.moveTo(startPoint.x, startPoint.y);
                    ctx.lineTo(movePoint.x, movePoint.y);
                    ctx.stroke();
                }
                canvasEle.addEventListener('mousedown', function(e) {
    
    
                    drawFlag = true;
                    startPoint = {
    
     
                        x: e.clientX,
                        y: e.clientY
                    };
                });
                canvasEle.addEventListener('mousemove', function(e) {
    
    
                    if (drawFlag) {
    
    
                        if (!drawFlag) return;
                        movePoint = {
    
    
                            x: e.clientX,
                            y: e.clientY
                        }
                        draw();
                        startPoint= movePoint;
                    }
                });
                canvasEle.addEventListener('mouseup', function(e) {
    
    
                    if (!drawFlag) return;
                    drawFlag = false;
                });


                // 通过事件模拟来兼容wrap端
                canvasEle.addEventListener('touchstart', onTouch);
                canvasEle.addEventListener('touchmove', onTouch);
                canvasEle.addEventListener('touchend', onTouch);

                function onTouch(e) {
    
    
                    let type = null;
                    let touch = e.touches[0] || e.changedTouches[0];
                    // console.log(e);
                    switch(e.type) {
    
    
                        case 'touchstart':
                            type = 'mousedown';
                            break;
                        case 'touchmove':
                            type = 'mousemove';
                            break;
                        case 'touchend':
                            type = 'mouseup';
                            break;
                        default:
                            break;
                    };
                    const newEvent = new MouseEvent(type, touch);
                    e.target.dispatchEvent(newEvent);
                }

            };


            document.querySelector('#btn').onclick = function() {
    
    
                let a = document.createElement('a');
                // image/png、image/jpeg、image/webp等等,默认为image/png格式;
                a.href = canvasEle.toDataURL();
                a.download = 'canvas' + new Date().getTime();
                a.target = '_blank';
                a.click();
            }

Guess you like

Origin blog.csdn.net/qq_48896417/article/details/126792337
Recommended