一个不错的HTML5 Canvas多层点击事件监听实例
程序员文章站
2023-12-05 15:50:46
写到一个多层点击事件的监听。觉得还是挺好玩的。于是把它从模块中抽化出来了,喜欢的朋友可以参考下... 14-04-29...
最近写一个html5的游戏框架。今天写到一个多层点击事件的监听。觉得还是挺好玩的。于是把它从模块中抽化出来了。以下代码只是一些思想。具体实现肯定不是那么丑陋
<!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>
复制代码
代码如下:<!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>
上一篇: HTML5 embed标签定义和用法详解