【问题标题】:html canvas trap left click and allow right click to pass through (pointer-events)html画布陷阱左键单击并允许右键单击通过(指针事件)
【发布时间】:2014-01-13 21:51:14
【问题描述】:

用例是我在几个 html 元素之上有一个 html 画布,用于侦听右键单击鼠标事件。我想使用鼠标左键在画布上绘图,同时使用右键单击与底层 html 元素交互。

我知道我可以通过将 css 属性指针事件设置为无来允许所有鼠标事件通过画布。但是我只想允许右键单击通过它。

实现此目的的一种方法可能是在画布上侦听右键单击,在回调中将指针事件设置为无,再次手动触发右键单击事件并将指针事件设置回自动。

顺便说一句,我正在使用 KineticsJS,但我不知道如何使用它手动触发鼠标事件。

任何建议将不胜感激。

【问题讨论】:

    标签: javascript html5-canvas mouseevent kineticjs


    【解决方案1】:

    引起我注意的有趣主题。基于this jQuery approach 和其他一些人提出解决方案很有趣。我不熟悉 KineticsJS,但这是一种普通的 javascript 方法

    本质上,您可以通过使用对象的尺寸/位置和onmousedownevent.which 来确定是否在背景元素上单击了右键,从而为右键单击伪造pointer-events:none。以下是该方法的示例,希望cmets解释清楚

    // Get all overlaying canvases
    var canvas = document.getElementsByTagName("canvas"), 
    // Get all elements that you want the click to fire on
        background = document.getElementsByClassName("background"); 
    
    // Use click location and dimensions/positioning to fake a click through
    function passThrough(e) { 
        // Allow only right click to pass through
        if(e.which == 2 || e.which == 3) { 
            // Check all background elements
            for(var i = 0; i < background.length; i++) { 
                // check if clicked point (taken from event) is inside element
                var mouseX = e.pageX;
                var mouseY = e.pageY;
                var obj = background[i];
                var width = obj.clientWidth;
                var height = obj.clientHeight;
    
                if (mouseX > obj.offsetLeft && mouseX < obj.offsetLeft + width 
                    && mouseY > obj.offsetTop && mouseY < obj.offsetTop + height) {
                    // Force click event if within dimensions
                    background[i].onclick(); 
                }
            }
        }
    }
    
    for(var i = 0; i < canvas.length; i++) {
        // Force our function when clicked
        canvas[i].onmousedown = passThrough; 
        // Prevent menu from appearing
        canvas[i].oncontextmenu = function(event) { event.returnDefault; return false; } 
    }
    for(var i = 0; i < background.length; i++) {
        // Toggle background when clicked (to show it works)
        background[i].onclick = function() { 
            if(this.style.background == "black") {
                this.style.background = "red";
            }
            else {
                this.style.background = "black";
            }
        }
    }
    

    希望它能满足你的需求!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-03-03
      • 2019-05-03
      • 2016-08-05
      • 1970-01-01
      • 1970-01-01
      • 2015-10-11
      • 1970-01-01
      相关资源
      最近更新 更多