5

我在 HTML5 画布上绘制了许多矩形,并希望能够右键单击这些框并显示上下文相关菜单。菜单应该特定于被点击的框的类型并且完全由用户指定,即它不应该包括重新加载、另存为、打印等...

任何人都可以给我任何指示吗?

谢谢,保罗

4

1 回答 1

9

您可以为上下文菜单添加EventListener 来处理鼠标右键请求:

// listen for contextmenu requests
canvas.addEventListener('contextmenu', handleContextmenu, false);  

然后在处理程序中,检查每个矩形是否有命中:

    function handleContextmenu(e){

      // get mouse position relative to the canvas
      var x=parseInt(e.clientX-offsetX);
      var y=parseInt(e.clientY-offsetY);


      // check each rect for hits
      for(var i=0;i<rects.length;i++){
          var rect=rects[i];
          var rectRight=rect.x+rect.width;
          var rectBottom=rect.y+rect.height;

          // if this rect is hit, display an alert
          if(x>=rect.x && x<=rectRight && y>=rect.y && y<=rectBottom  ){
              alert("Context menu request on the "+rect.color+" rectangle.");
          }
      }

      // prevents the usual context from popping up
      e.preventDefault()
      return(false); 
    }

这是工作代码(没有 jsFiddle,因为在 X-Domain iframe 中没有右键单击):

<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>

<style>
    body{ background-color: ivory; }
    canvas{border:1px solid red;}
</style>

<script>
$(function(){

    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");

    var canvasOffset=$("#canvas").offset();
    var offsetX=canvasOffset.left;
    var offsetY=canvasOffset.top;

    var rects=[];

    rects.push({x:50,y:50,width:50,height:50,color:"red"});
    rects.push({x:150,y:100,width:75,height:75,color:"blue"});

    ctx.clearRect(0,0,canvas.width,canvas.height);
    for(var i=0;i<rects.length;i++){
        var rect=rects[i];
        ctx.beginPath();
        ctx.fillStyle=rect.color;
        ctx.rect(rect.x,rect.y,rect.width,rect.height);
        ctx.fill();
    }

    // listen for contextmenu requests
    canvas.addEventListener('contextmenu', handleMouseDown, false);  

    function handleMouseDown(e){

      // get mouse position relative to the canvas
      var x=parseInt(e.clientX-offsetX);
      var y=parseInt(e.clientY-offsetY);


      // check each rect for hits
      for(var i=0;i<rects.length;i++){
          var rect=rects[i];
          var rectRight=rect.x+rect.width;
          var rectBottom=rect.y+rect.height;

          // check each rect for hits
          if(x>=rect.x && x<=rectRight && y>=rect.y && y<=rectBottom  ){
              alert("Context menu request on the "+rect.color+" rectangle.");
          }
      }

      // prevents the usual context from popping up
      e.preventDefault()
      return(false); 
    }

}); // end $(function(){});
</script>

</head>

<body>
    <canvas id="canvas" width=300 height=300></canvas>
</body>
</html>
于 2013-06-13T17:29:21.770 回答