A good HTML5 Canvas multi-layer Click Event listener instance

Source: Internet
Author: User

Comments: Write to a multi-layer Click Event listener. I think it is quite fun. So I extracted it from the module. For more information, see a recently written HTML5 game framework. Today, I wrote a multi-layer Click Event listener. I think it is quite fun. So we extracted it from the module. The following code is just a few ideas. The specific implementation is certainly not so ugly

The Code is as follows:
<! Doctype html>
<Html lang = "en">
<Head>
<Meta charset = "UTF-8">
<Title> Document </title>
<Style type = "text/css">
. Box> canvas {
Position: absolute;
}
</Style>
</Head>
<Body>
<Div class = "box">
<Canvas id = "layer1" width = "200" height = "200"> </canvas>
<Canvas id = "layer2" width = "500" height = "500"> </canvas>
</Div>
<Script type = "text/javascript">
Function getRect (obj ){
Var x1 = obj. offsetLeft;
Var y1 = obj. offsetTop;
Var x2 = x1 + obj. offsetWidth;
Var y2 = y1 + obj. offsetHeight;
Return {
X1: x1,
Y1: y1,
X2: x2,
Y2: y2
};
}
Function inside (x, y, rect ){
If (x> rect. x1 & x <rect. x2 & y> rect. y1 & y <rect. y2 ){
Return true;
}
Else {
Return false;
}
}
Var trigger = {};
Trigger. list = [];
Trigger. listen = function (){
Var list = trigger. list;
Document. addEventListener ('click', function (evt ){
For (var I = 0; I <list. length; ++ I ){
List [I] (evt );
}
});
};
Trigger. listen ();
Var l1 = document. getElementById ('layer1 ');
Var l2 = document. getElementById ('layer2 ');
Var dl1 = function (evt ){
If (inside (evt. clientX, evt. clientY, getRect (l1 ))){
Console. log ('click ');
}
}
Trigger. list. push (dl1 );
Var dl2 = function (evt ){
If (inside (evt. clientX, evt. clientY, getRect (l2 ))){
Console. log ('click2 ');
}
}
Trigger. list. push (dl2 );
</Script>
</Body>
</Html>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.