我正试图让我在画布上制作的圆圈有一个onclick事件。我尝试了以下但没有成功。如果有人能提供一些指示,那就太好了。
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="type"></div>
<canvas id="ctx2" width="500" height="500" style="border: solid 1px;"></canvas>
<script>
var ctx = document.getElementById("ctx2").getContext("2d");
//var message = 'Hello John, this is your canvas.';
//ctx.fillStyle = 'red';
//ctx.font = '30px Arial';
//ctx.opacity = 0;
//ctx.fillText(message,50,50);
ctx.beginPath();
ctx.arc(100,75,50,0,2*Math.PI);
ctx.stroke();
ctx.onclick = displayDate(); // This is what I used (stack overflow)
function displayDate() {
document.getElementById("type").innerHTML = Date();
}
document.getElementById("type").innerHTML = typeof ctx
</script>
</body>
</html>
答案 0 :(得分:1)
您需要将事件侦听器添加到画布,然后检查&#34;单击&#34;事件坐标位于您创建的圆形区域内。 jsFiddle示例:https://jsfiddle.net/aL2epngo/
var circle = {x:100,y:75, r:50};
function displayDate() {
document.getElementById("type").innerHTML = Date();
}
function checkBoundaries(x,y){
var clicked = false;
if(x >=circle.x - circle.r && x <= circle.x+circle.r){
if(y >= circle.y- circle.r && y <= circle.y+circle.r){
clicked = true;
}
}
return clicked;
}
function clickHandler(e){
var canvas = document.getElementsByTagName("canvas")[0];
var x = e.pageX ? e.pageX: e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
var y = e.pageY ? e.pageY: e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
x -= canvas.offsetLeft;
y -= canvas.offsetTop;
if( checkBoundaries(x,y) ){
displayDate()
}
}
答案 1 :(得分:-1)
你可以用
ctx.addEventListener('click', function(event) {
displayDate();
},false);
//or
canvas.addEventListener("mousedown",function(){
displayDate();
},false)
如果您满意,那么投票给我