如何在canvas元素中添加一个简单的onClick事件处理程序? [英] How do I add a simple onClick event handler to a canvas element?

查看:932
本文介绍了如何在canvas元素中添加一个简单的onClick事件处理程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一名经验丰富的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!); }; - 没有
var context = elem.getContext('2d');
context.fillStyle ='#05EFFF';
context.fillRect(0,0,150,100);
< / script>

< / body>

解决方案

当您绘制到画布元素时,您只需在立即模式



绘制的元素(形状,线条,图像)除了他们使用的像素及其颜色。



因此,要在画布上获得点击事件 元素(形状),您需要捕获画布上的点击事件 HTML元素,并使用一些数学来确定哪个元素被点击,只要您存储元素的宽度/高度和x / y偏移量。



要添加单击事件到您的画布元素,使用...

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

确定单击元素

  var elem = document.getElementById('myCanvas'),
elemLeft = elem.offsetLeft,
elemTop = elem.offsetTop ,
context = elem.getContext('2d'),
elements = [];

//为点击事件添加事件侦听器。
elem.addEventListener('click',function(event){
var x = event.pageX - elemLeft,
y = event.pageY - elemTop;

/ /点击偏移和元素之间的碰撞检测
elements.forEach(function(element){
if(y> element.top&&&&&&&&&& amp;< 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
});

//渲染元素。
elements.forEach(function(element){
context.fillStyle = element.colour;
context.fillRect(element.left,element.top,element.width,element.height);
});

jsFiddle



此代码将点击事件附加到 canvas 元素,然后将一个形状(在我的代码中称为元素)推送到元素数组。您可以在此处添加任意数量。



创建对象数组的目的是,我们可以稍后查询其属性。在所有元素被推到数组之后,我们根据它们的属性循环遍历并呈现每个元素。



点击事件被触发,代码循环遍历元素,并确定点击是否超过元素数组中的任何元素。如果是这样,它会触发一个 alert(),这可以很容易地被修改为执行某些操作,例如删除数组项,在这种情况下,您需要一个单独的渲染功能来更新画布



为了完整,为什么你的尝试不起作用。 ..

  elem.onClick = alert(hello world); //显示警报而不点击

这是分配返回值 alert( ) onClick 属性 elem 。它正在立即调用 alert()

  elem.onClick =警戒('你好世界'); //显示警报而不点击

在JavaScript中,'在语义上相同,词法分析器可能使用 ['] 作为引号。

  elem.onClick =alert('hello world!'); //不做任何事情,即使点击

您正在将一个字符串分配给 onClick 属性 elem

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

JavaScript区分大小写。 onclick 属性是附加事件处理程序的古老方法。它只允许一个事件附加属性,并且当序列化HTML时,事件可能会丢失。

  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);
});​

jsFiddle.

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屋!

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