canvas笔记-canvas中用户与图形交互

运行截图如下:

点击某个圆后:

代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<canvas id="canvas" style="border: 1px solid #aaa; display: block; margin: 50px auto;">
    当前浏览器不支持canvas
</canvas>

<script>

    let balls = [];
    let canvas = document.getElementById("canvas");
    let context = canvas.getContext("2d");

    window.onload = function(){

        canvas.width = 800;
        canvas.height = 800;

        for(let i = 0; i < 10; i++){

            let ball = {
                x: Math.random() * canvas.width,
                y: Math.random() * canvas.height,
                r: Math.random() * 50 + 20
            };
            balls[i] = ball;
        }

        draw();
        canvas.addEventListener("mouseup", detect);
    }

    function draw(){

        for(let i = 0; i < balls.length; i++){

            context.beginPath();
            context.arc(balls[i].x, balls[i].y, balls[i].r, 0, Math.PI * 2);
            context.fillStyle = "#058";
            context.fill();
        }
    }

    function detect(event){

        let x = event.clientX - canvas.getBoundingClientRect().left;
        let y = event.clientY - canvas.getBoundingClientRect().top;

        console.log("x:" + x + "  y:" + y);

        for(let i = 0; i < balls.length; i++){

            context.beginPath();
            context.arc(balls[i].x, balls[i].y, balls[i].r, 0, Math.PI * 2);

            if(context.isPointInPath(x, y)){

                context.fillStyle = "red";
                context.fill();
            }
        }
    }

</script>

</body>
</html>

这里简单说下逻辑,通过canvas.addEventListener监听鼠标弹起的事件,然后通过

let x = event.clientX - canvas.getBoundingClientRect().left;
let y = event.clientY - canvas.getBoundingClientRect().top;

获取当前再canvas中的点的坐标,每次鼠标弹起的时候就进行重绘。

if(context.isPointInPath(x, y)){

    context.fillStyle = "red";
    context.fill();
}

isPointInPath()方法当点位于当前路径中,则返回true,否则返回false

 

 

下面给出另外一种方法:

function mouseoverFunction(event){

  let mouseX = event.offsetX;
  let mouseY = event.offsetY;

  for(let i = 0; i < XXXXXXXObjects.length; i++){

    if(
      (XXXXXXXObjects[i].x <= mouseX && (XXXXXXXObjects[i].x + XXXXXXXObjects[i].width) >= mouseX) &&
      (XXXXXXXObjects[i].y <= mouseY && (XXXXXXXObjects[i].y + XXXXXXXObjects[i].height) >= mouseY)
    ){

      XXXXXXXObjects[i].onClicked();
    }
  }
}

通过这种方式也可以获取x,y在canvas中的坐标,并且判断数组里面的图形,x,y是否在点击的坐标中,如果是就调用onClicked函数。

展开阅读全文
©️2020 CSDN 皮肤主题: 数字20 设计师: CSDN官方博客 返回首页
实付0元
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值