发生事件时获取HTML5画布图形(Arc)的尺寸 [英] Get dimensions of a HTML5 canvas graphic (Arc), when an event occurs

查看:103
本文介绍了发生事件时获取HTML5画布图形(Arc)的尺寸的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是:当发出单击",鼠标悬停"等事件时,我应该如何做逻辑和数学部分,以便计算每个弧的位置.

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.

要考虑的要点:

.线宽

..它们是圆角线.

.弧长百分比.

.第一个元素是ej:z索引位置.

. Which element is first, ej: z-index position.

我的源代码

谢谢您的时间.

推荐答案

有一个方便的 isPointInStroke() 方法,仅用于此目的.

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

要考虑z-index,只需按照您绘制的相反顺序进行检查:

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 = new Path2D();
  p.arc(centerX, centerY, rad, -Math.PI/2, obj.a-Math.PI/2);
  obj.path = p;
});

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

function draw() {
  ctx.clearRect(0,0,canvas.width,canvas.height);
  // since we sorted first => higher z-index
  for(let i = pathes.length-1; i>=0; i--) {
    let p = pathes[i];
    ctx.strokeStyle = p.hovered ? 'green' : p.color;
    ctx.stroke(p.path);
  };
}
function checkHovering(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}

<canvas id="canvas"></canvas>

如果您需要IE支持,则此polyfill 应该可以.

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

这篇关于发生事件时获取HTML5画布图形(Arc)的尺寸的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆