# 自定义事件与事件模拟

# 一、自定义事件

# 1、js自定义事件有三种方式

  • new CustomEvent('wheelup', {});
  • new Event('wheelup', {})
  • document.createEvent('HTMLEvents'); initEvent('wheelup', false, false) 其中第三中方式必须进行初始化
// 以实现监听鼠标滚轮上滚或者下滚动事件为例子
// 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);
            })
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35

# 2、createEvent()

1、createEvent()方法返回新创建的Event对象,支持一个参数,表示事件类型,具体见下表: 在这里插入图片描述 2、initEvent()方法用于初始化通过DocumentEvent接口创建的Event的值。 支持三个参数:initEvent(eventName, canBubble, preventDefault) 分别表示:

  • 事件名称
  • 是否可以冒泡
  • 是否阻止事件的默认操作

# 二、事件模拟

1、事件模拟通常是用来兼容wap端和pc端的效果

以wap端兼容pc端的canvas画板效果为例子:

<!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>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// 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();
            }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
Last Updated: 6/12/2025, 1:09:29 AM