如何向canvas元素添加一个简单的onClick事件处理程序? [英] How do I add a simple onClick event handler to a canvas element?
问题描述
我是一个有经验的Java程序员,但大约十年来第一次看到一些JavaScript / HTML5的东西。我完全不知道应该是最简单的事情。
作为一个例子,我只是想绘制一些东西,并添加一个事件处理程序。我相信我做的事情是愚蠢的,但我已经搜索了,没有建议(例如这个问题的答案:添加onclick属性以使用JavaScript输入)。我使用的是Firefox 10.0.1。我的代码如下。你会看到几条带注释的行,每行的末尾是什么(或什么不发生)的描述。
这里有什么正确的语法?我会疯了!
< html>
< body>
< canvas id =myCanvaswidth =300height =150/>
< script language =JavaScript>
var elem = document.getElementById('myCanvas');
// elem.onClick = alert(hello world); - 显示警报,而不单击
// elem.onClick = alert('hello world'); - 显示警报,而不单击
// elem.onClick =alert('hello world!'); - 什么都不做,即使点击
// elem.onClick = function(){alert('hello world!'); }; - 什么都不做
// elem.onClick = function(){alert(hello world!); }; - do nothing
var context = elem.getContext('2d');
context.fillStyle ='#05EFFF';
context.fillRect(0,0,150,100);
< / script>
< / body>
当你绘制到 canvas
元素时,你只需要在立即模式。
绘制的元素(形状,线条,图像)他们使用的像素和它们的颜色。
因此,在画布上获得点击 $ c> 元素(shape),您需要捕获
canvas
HTML元素上的点击事件,并使用一些数学来确定点击了哪个元素,
要添加点击
事件 canvas
元素,使用...
canvas.addEventListener点击',function(){},false);
要确定要点击的元素 ...
var elem = document.getElementById('myCanvas'),
elemLeft = elem.offsetLeft,
elemTop = elem.offsetTop ,
context = elem.getContext('2d'),
elements = [];
//为`click`事件添加事件监听器。
elem.addEventListener('click',function(event){
var x = event.pageX - elemLeft,
y = event.pageY - elemTop;
/ /单击的偏移和元素之间的碰撞检测。
elements.forEach(function(element){
if(y> element.top& y< element.top + element.height
& x> element.left&& x< element.left + element.width){
alert('clicked a element');
}
});
},false);
//添加元素。
elements.push({
color:'#05EFFF',
width:150,
height:100,
top:20,
left: 15
});
//渲染元素。
element.forEach(function(element){
context.fillStyle = element.colour;
context.fillRect(element.left,element.top,element.width,element.height);
});
此代码将点击
事件附加到 canvas
元素,然后将一个形状(在我的代码中称为元素
)推送到元素
数组。
创建一个对象数组的目的是为了我们以后可以查询它们的属性。在所有元素都被推入数组之后,我们根据它们的属性循环并渲染每个元素。
当点击
事件被触发,代码循环遍历元素,并确定点击是否超过元素
数组中的任何元素。如果是这样,它会触发一个 alert()
,它可以很容易地被修改以执行一些操作,例如删除数组项,在这种情况下你需要一个单独的
为了完整性,为什么你的尝试不起作用。 ..
elem.onClick = alert(hello world); //显示警报而不单击
这是分配 alert )到
elem
的 onClick
属性。它立即调用 alert()
。
elem.onClick = alert('hello world'); //在不点击
的情况下显示提醒在 $ c>和
在语义上是相同的,词法分析器可能使用 [']
elem.onClick =alert('hello world!'); //不指定任何内容,即使点击
您正在为 onClick
属性 elem
。
.onClick = function(){alert('hello world!'); }; // does nothing
JavaScript区分大小写。 onclick
属性是附加事件处理程序的古老方法。
elem.onClick = function(){alert(hello world!); }; // does nothing
同样,'===
。
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!
<html>
<body>
<canvas id="myCanvas" width="300" height="150"/>
<script language="JavaScript">
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);
</script>
</body>
解决方案 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, ' === "
.
这篇关于如何向canvas元素添加一个简单的onClick事件处理程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!