zoukankan      html  css  js  c++  java
  • canvas 使用 isPointInPath() 判断鼠标位置是否在绘制的元素上

    canvas 里绘制的图形不是一个实体 DOM,所以要给每个绘制的图形添加事件操作比给 DOM 添加事件要复杂很多。

    所以,我们需要使用一个 canvas 的 isPointInPath(x, y) 方法,来获取鼠标相对于浏览器的坐标,然后还需要计算出鼠标相对于 canvas 画布的坐标,最后通过 isPointInPath(x, y) 方法判断此坐标是否在绘制的元素上,进行相应的操作。

    isPointInPath() 方法是针对的当前绘制的路径,而鼠标在执行操作的时候,我们会根据需要监听鼠标的事件,当鼠标事件符合我们要求的时候,就对画布进行重绘。在重绘的时候,每画一条路径就调用一次 isPointInPath(x, y) 方法,判断鼠标操作的点是不是在这个绘制的元素身上,如果在,就可以对当前绘制的这个元素进行自定义操作了。

    以下是绘制两个图形,并监听 mousemove 事件,来判断鼠标是否在图形上的 demo:

    <style type="text/css">
    *{margin:0;padding:0;}
    .canvas-box {position: relative;}
    canvas {box-shadow: 0 0 10px rgba(0,0,0,0.2) }
    </style>
    
    <div class="canvas-box"> 
     <canvas id="cvs" width="500" height="400">不支持canvas</canvas>
    </div>
    
    <script>
    var cvs = document.getElementById('cvs');
    var ctx = cvs.getContext('2d');
    // 封装绘制的图形
    function draw () {
      ctx.fillStyle = '#000';
      ctx.beginPath();
      ctx.moveTo(100,100);
      ctx.bezierCurveTo(110,110,199,278,300,379);
      ctx.lineTo(400,100)
      ctx.closePath();
    }
    function circle () {
      ctx.fillStyle = '#000';
      ctx.beginPath();
      ctx.arc(100,200,50,0,Math.PI*2)
      ctx.closePath();
    }
    // 初始化绘制图形
    draw();
    ctx.fill()
    circle();
    ctx.fill()
    var fns = [draw,circle];
    // 监听鼠标事件
    cvs.onmousemove = function (e) {
      // 得到鼠标的坐标
      var x = e.pageX, y =e.pageY;
      ctx.clearRect(0,0,400,300)
      // 遍历绘制图形
      for(var i = fns.length; i--;) {
        fns[i]();
        // 每绘制一个图形就判断一次当前鼠标的坐标是否在这个图形上,然后进行自定义操作
        if(ctx.isPointInPath(x,y)) {
          ctx.fillStyle = "#f00"
        } else {
          ctx.fillStyle = "#000"
        }
        ctx.fill()
      }
    }
    </script> 
  • 相关阅读:
    IIS常见500错误解决方案
    发送邮件代码
    IIS站点/虚拟目录中访问共享目录(UNC)
    简简单单,一目了然C#与Matlab
    [转载]C#——DataGridView分页功能的实现
    博客之旅
    ASP.Net, Php , Java/Java EE?好困惑
    【转载】DataGridView中虚拟模式(Virtual Mode)用法
    selenium4.0降级为3版本
    web自动化中影响页面定位的场景有哪些?
  • 原文地址:https://www.cnblogs.com/3body/p/6839675.html
Copyright © 2011-2022 走看看