如何在画布元素(arc)中添加onClick事件处理程序?

时间:2018-12-16 16:28:25

标签: javascript canvas javascript-events html5-canvas

我将元素推到数组,然后循环它们。我如何做到以下。我想单击一个圆圈区域,然后发出警报。我发现答案是矩形,所以圆形怎么办?     

Unable to infer closure type in the current context

2 个答案:

答案 0 :(得分:1)

您需要在调用方法isPointInPath之前重绘形状。

我已经在代码中添加了检测鼠标位置的功能以及另一个绘制元素的功能。希望对您有所帮助。

var elements = [];
var canvas = document.getElementById("myCanvas");
canvas.width = "500";
canvas.height = "500";
var context = canvas.getContext("2d");

var mouse;

elements.push({
  colour: "#112F41",
  x: 200,
  y: 240,
  r: 100,
  sAngle: 0,
  eAngle: 2 * Math.PI
});

elements.forEach(element => {
  drawElement(element, context);
});

canvas.addEventListener(
  "click",
  function(event) {
    mouse = oMousePos(canvas, event)
    elements.forEach(function(element) {
      drawElement(element, context);
      if(context.isPointInPath(mouse.x, mouse.y)){console.log(mouse)}else{console.log("not in path")}
    });
  },
  false
);

function drawElement(element, context) {
  context.strokeStyle = element.colour;
  context.arc(element.x, element.y, element.r, element.sAngle, element.eAngle);
  context.lineWidth = 2;

  context.stroke();
}

function oMousePos(canvas, evt) {
  var ClientRect = canvas.getBoundingClientRect();
  return { //objeto
    x: Math.round(evt.clientX - ClientRect.left),
    y: Math.round(evt.clientY - ClientRect.top)
  }
}
canvas {
  border:1px solid;
}
<canvas id="myCanvas"></canvas>

答案 1 :(得分:0)

您还可以使用三角函数来计算鼠标和圆之间的距离。 我添加了一个pointInCircle方法,如果鼠标在圆形元素内,则返回true;否则,返回false。

简单的Pythagorean theorem

  

注意:此方法还提供完整的浏览器支持。

var elements = [];
var canvas = document.getElementById("myCanvas");
canvas.width = "500";
canvas.height = "500";
var context = canvas.getContext("2d");

var mouse;

elements.push({
  colour: "#112F41",
  x: 200,
  y: 240,
  r: 100,
  sAngle: 0,
  eAngle: 2 * Math.PI
});

elements.forEach(element => {
  drawElement(element, context);
});

canvas.addEventListener(
  "click",
  function(event) {
    mouse = oMousePos(canvas, event)
    elements.forEach(function(element) {
      drawElement(element, context);
      // method using point to circle collision detection
      if (pointInCircle(element, mouse)) {
        console.log(mouse)
      } else {
        console.log("not in path")
      }
    });
  },
  false
);

// pointInCircle
function pointInCircle(circle, mouse) {
   let dx = circle.x - mouse.x;
   let dy = circle.y - mouse.y;
   let dist = Math.sqrt(dx*dx + dy*dy);
   
   if (dist < circle.r) return true;
   return false
}

function drawElement(element, context) {
  context.strokeStyle = element.colour;
  context.arc(element.x, element.y, element.r, element.sAngle, element.eAngle);
  context.lineWidth = 2;

  context.stroke();
}

function oMousePos(canvas, evt) {
  var ClientRect = canvas.getBoundingClientRect();
  return {
    x: Math.round(evt.clientX - ClientRect.left),
    y: Math.round(evt.clientY - ClientRect.top)
  }
}
<canvas id="myCanvas"></canvas>