gpt4 book ai didi

javascript - 如何将 onClick 事件处理程序添加到 Canvas 元素 (arc)?

转载 作者:行者123 更新时间:2023-12-03 00:32:22 24 4
gpt4 key购买 nike

我将一个元素插入数组,以便循环它们。我如何做以下。我想单击一个圆形区域,然后发出警报。我发现答案是矩形,那么圆形又如何呢?

<canvas id="myCanvas" width="500" height="500" style="border:1px solid #d3d3d3;"></canvas>

<script>

var elements = [];
elemLeft = canvas.offsetLeft,
elemTop = canvas.offsetTop;


var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");

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

elements.forEach(function(element) {
context.strokeStyle = element.colour;
context.arc(element.x, element.y, element.r, element.sAngle, element.eAngle);
context.lineWidth = 20;

context.stroke();
});

canvas.addEventListener('click', function(event) {
var x = event.pageX - elemLeft,
y = event.pageY - elemTop;
console.log(x, y);
elements.forEach(function(element) {
//??????
});

}, false);

</script>

最佳答案

在调用方法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>

关于javascript - 如何将 onClick 事件处理程序添加到 Canvas 元素 (arc)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53804166/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com