canvas 判断哪个元素被点击_如何在canvas元素中添加一个简单的onClick事件处理程序?...

在JavaScript和HTML5的Canvas元素上添加点击事件处理并不直观。由于Canvas本质上是位图,所以需要监听Canvas元素的点击事件,然后通过坐标判断点击的位置。正确的方法是使用addEventListener绑定点击事件,并通过循环元素数组进行碰撞检测来确定点击了哪个元素。
摘要由CSDN通过智能技术生成

I'm an experienced Java programmer but am looking at some JavaScript/HTML5 stuff for the first time in about a decade. I'm completely stumped on what should be the simplest thing ever.

As an example I just wanted to draw something and add an event handler to it. I'm sure I'm doing something stupid, but I've searched all over and nothing that is suggested (e.g. the answer to this question: Add onclick property to input with JavaScript) works. I'm using Firefox 10.0.1. My code follows. You'll see several commented lines and at the end of each is a description of what (or what doesn't) happen.

What's the correct syntax here? I'm going crazy!

var elem = document.getElementById('myCanvas');

// elem.onClick = alert("hello world"); - displays alert without clicking

// elem.onClick = alert('hello world'); - displays alert without clicking

// elem.onClick = "alert('hello world!')"; - does nothing, even with clicking

// elem.onClick = function() { alert('hello world!'); }; - does nothing

// elem.onClick = function() { alert("hello world!"); }; - does nothing

var context = elem.getContext('2d');

context.fillStyle = '#05EFFF';

context.fillRect(0, 0, 150, 100);

解决方案

When you draw to a canvas element, you are simply drawing a bitmap in immediate mode.

The elements (shapes, lines, images) that are drawn have no representation besides the pixels they use and their colour.

Therefore, to get a click event on a canvas element (shape), you need to capture click events on the canvas HTML element and use some math to determine which element was clicked, provided you are storing the elements' width/height and x/y offset.

To add a click event to your canvas element, use...

canvas.addEventListener('click', function() { }, false);

To determine what element was clicked...

var elem = document.getElementById('myCanvas'),

elemLeft = elem.offsetLeft,

elemTop = elem.offsetTop,

context = elem.getContext('2d'),

elements = [];

// Add event listener for `click` events.

elem.addEventListener('click', function(event) {

var x = event.pageX - elemLeft,

y = event.pageY - elemTop;

// Collision detection between clicked offset and element.

elements.forEach(function(element) {

if (y > element.top && y < element.top + element.height

&& x > element.left && x < element.left + element.width) {

alert('clicked an element');

}

});

}, false);

// Add element.

elements.push({

colour: '#05EFFF',

width: 150,

height: 100,

top: 20,

left: 15

});

// Render elements.

elements.forEach(function(element) {

context.fillStyle = element.colour;

context.fillRect(element.left, element.top, element.width, element.height);

});​

This code attaches a click event to the canvas element, and then pushes one shape (called an element in my code) to an elements array. You could add as many as you wish here.

The purpose of creating an array of objects is so we can query their properties later. After all the elements have been pushed onto the array, we loop through and render each one based on their properties.

When the click event is triggered, the code loops through the elements and determines if the click was over any of the elements in the elements array. If so, it fires an alert(), which could easily be modified to do something such as remove the array item, in which case you'd need a separate render function to update the canvas.

For completeness, why your attempts didn't work...

elem.onClick = alert("hello world"); // displays alert without clicking

This is assigning the return value of alert() to the onClick property of elem. It is immediately invoking the alert().

elem.onClick = alert('hello world'); // displays alert without clicking

In JavaScript, the ' and " are semantically identical, the lexer probably uses ['"] for quotes.

elem.onClick = "alert('hello world!')"; // does nothing, even with clicking

You are assigning a string to the onClick property of elem.

elem.onClick = function() { alert('hello world!'); }; // does nothing

JavaScript is case sensitive. The onclick property is the archaic method of attaching event handlers. It only allows one event to be attached with the property and the event can be lost when serialising the HTML.

elem.onClick = function() { alert("hello world!"); }; // does nothing

Again, ' === ".

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值