Skip to content Skip to sidebar Skip to footer

Get Dimensions Of A Html5 Canvas Graphic (arc), When An Event Occurs

My question is: how should I do the logical and mathematical part, in order to calculate the position of each arc, when an event is emitted: 'click', 'mouseover', etc. Points to co

Solution 1:

There is a convenient isPointInStroke() method, just for that.

To take the z-index into consideration, just check in the reverse order you drew:

const ctx = canvas.getContext('2d');
const centerX = canvas.width/2;
const centerY = canvas.height/2;
const rad = Math.min(centerX, centerY) * 0.75;
const pathes = [
  {
    a: Math.PI/4,
    color: 'white'
  },
  {
    a: Math.PI/1.5,
    color: 'cyan'
  },
  {
    a: Math.PI,
    color: 'violet'
  },
  {
    a: Math.PI*2,
    color: 'gray'
  }
];
pathes.forEach(obj => {
  const p = newPath2D();
  p.arc(centerX, centerY, rad, -Math.PI/2, obj.a-Math.PI/2);
  obj.path = p;
});

ctx.lineWidth = 12;
ctx.lineCap = 'round';

functiondraw() {
  ctx.clearRect(0,0,canvas.width,canvas.height);
  // since we sorted first => higher z-indexfor(let i = pathes.length-1; i>=0; i--) {
    let p = pathes[i];
    ctx.strokeStyle = p.hovered ? 'green' : p.color;
    ctx.stroke(p.path);
  };
}
functioncheckHovering(evt) {
  const rect = canvas.getBoundingClientRect();
  const x = evt.clientX - rect.left;
  const y = evt.clientY - rect.top;
  let found = false;
  pathes.forEach(obj => {
    if(found) {
      obj.hovered = false;
    }
    else {
      found = obj.hovered = ctx.isPointInStroke(obj.path, x, y);
    }
  });
  draw();
}

draw();
canvas.onmousemove = canvas.onclick = checkHovering;

 
canvas{background: lightgray}
<canvasid="canvas"></canvas>

And if you need IE support, this polyfill should do.

Solution 2:

It's much better to "remember" the objects you drew, rather than drawing them and trying to gather what they are from what you drew. So, for example, you could store the render information: (I don't know typescript)

let curves = [{start: 30, length: 40, color: "white"}/*...*/];

Then, render it:

ctx.fillStyle = curve.color;
ctx.arc(CENTER_X, CENTER_Y, RADIUS, percentToRadians(curve.start), percentToRadians(curve.start + curve.length));

Then, to retrieve the information, simply reference curves. The z values depend on the order of the render queue (curves).

Of course, you probably could gather that data from the canvas, but I wouldn't recommend it.

Post a Comment for "Get Dimensions Of A Html5 Canvas Graphic (arc), When An Event Occurs"