当前位置:网站首页>《canvas》之第13章 事件操作
《canvas》之第13章 事件操作
2022-06-29 13:55:00 【yxqq378287007】
《canvas》之第13章 事件操作
第13章 事件操作
13.1 canvas进阶简介
canvas api + JavaScript。
13.2 鼠标事件
13.2.1 鼠标事件简介
- 鼠标按下,mousedown
- 鼠标松开,mouseup
- 鼠标移动,mousemove
拖动效果实现,mousedown判断选中图形或元素,mousemove拖动选中图形或元素,mouseup停止拖动。
13.2.2 获取鼠标指针位置
鼠标指针在画布上的相对坐标。
pageX,pageY与clientX,clientY。
鼠标指针当前位置属性。element.offsetLeft,element.offsetTop。
元素的偏移位置。tools.js
//定义工具函数集
window.tools = {};
//获取鼠标当前位置(相对坐标)
window.tools.getMouse = function (element) {
var mouse = { x: 0, y: 0 };
element.addEventListener("mousemove", function (e) {
var x, y;
var e = e || window.event;//IE中,event对象是window的一个属性
if (e.pageX || e.pageY) {//兼容Firefox、chrome、IE9及以上
x = e.pageX;
y = e.pageY;
}
else {//兼容混杂模式下safari、chrome,IE8及以下
x = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
y = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
}
//减去canvas偏移,获取canvas中相对坐标值
x -= element.offsetLeft;
y -= element.offsetTop;
mouse.x = x;
mouse.y = y;
}, false);
return mouse;
}
- 鼠标移动事件
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<meta charset="utf-8" />
<script src="js/tools.js"></script>
<script type="text/javascript"> function $$(id) {
return document.getElementById(id); } window.onload = function () {
var cnv = $$("canvas"); var cxt = cnv.getContext("2d"); var txt = $$("txt"); var mouse = tools.getMouse(cnv); cnv.addEventListener("mousemove", function () {
txt.innerHTML = "鼠标当前坐标为:(" + mouse.x + "," + mouse.y + ")"; }, false); } </script>
</head>
<body>
<canvas id="canvas" width="200" height="150" style="border:1px solid silver;"></canvas>
<p id="txt"></p>
</body>
</html>
13.3 键盘事件
13.3.1 键盘事件简介
- 键盘松下,keydown
- 键盘松开,keyup
canvas元素不支持键盘事件,通过window对象实现canvas中键盘事件的监听。
window.addEventListener(type, fn, false)
- type,事件类型
- fn,事件处理函数
- false(默认可省略),false:冒泡,从里到外,true:捕获,从外到里。
13.3.2 获取物体移动方向
- 常用按键对应keyCode
| 按键 | keyCode |
|---|---|
| W上 | 87 |
| S下 | 83 |
| A左 | 65 |
| D右 | 68 |
| ↑ | 38 |
| ↓ | 40 |
| ← | 37 |
| → | 39 |
//获取键盘控制方向
window.tools.getKey = function () {
var key = {};
window.addEventListener("keydown", function (e) {
if (e.keyCode == 38 || e.keyCode == 87) {
key.direction = "up";
} else if (e.keyCode == 39 || e.keyCode == 68) {
key.direction = "right";
} else if (e.keyCode == 40 || e.keyCode == 83) {
key.direction = "down";
} else if (e.keyCode == 37 || e.keyCode == 65) {
key.direction = "left";
} else {
key.direction = "";
}
}, false);
return key;
}
- 键盘事件
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<meta charset="utf-8" />
<script src="js/tools.js"></script>
<script type="text/javascript"> function $$(id) {
return document.getElementById(id); } window.onload = function () {
var cnv = $$("canvas"); var cxt = cnv.getContext("2d"); //初始化一个圆形 drawBall(cnv.width / 2, cnv.height / 2); //初始化变量 var x = 100; var y = 75; //获取按键方向 var key = tools.getKey(); //添加鼠标按下事件 window.addEventListener("keydown", function (e) {
//清除整个Canvas,以便重绘新的圆形 cxt.clearRect(0, 0, cnv.width, cnv.height); //根据key.direction的值,判断小球移动方向 switch (key.direction) {
case "up": y -= 2; break; case "down": y += 2; break; case "left": x -= 2; break; case "right": x += 2; break; }; drawBall(x, y); }, false); //定义绘制小球的函数 function drawBall(x, y) {
cxt.beginPath(); cxt.arc(x, y, 20, 0, 360 * Math.PI / 180, true); cxt.closePath(); cxt.fillStyle = "#6699FF"; cxt.fill(); } } </script>
</head>
<body>
<canvas id="canvas" width="200" height="150" style="border:1px solid silver;"></canvas>
</body>
</html>
13.4 循环事件
setInterval()方法不能准确控制动画的帧率,需手动设置间隔时间。requestAnimationFrame()方法无需手动设置间隔时间,回根据浏览器绘制帧率自动调整。
(function frame(){
window.requestAnimationFrame(frame); //不断调用frame()函数
cxt.clearRect(0, 0, cnv.width, cnv.height);
})(); //自执行函数frame()
//动画循环,兼容各大浏览器
window.requestAnimationFrame = (
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.msRequestAnimationFrame ||
window.oRequestAnimationFrame ||
function (callback) {
return window.setTimeout(callback, 1000 / 60);
}
);
- 循环事件
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<meta charset="utf-8" />
<script src="js/tools.js"></script>
<script type="text/javascript"> function $$(id) {
return document.getElementById(id); } window.onload = function () {
var cnv = $$("canvas"); var cxt = cnv.getContext("2d"); //初始化变量,也就是初始化圆的X轴坐标为0 var x = 0; //动画循环 (function frame() {
window.requestAnimationFrame(frame); //每次动画循环都先清空画布,再重绘新的图形 cxt.clearRect(0, 0, cnv.width, cnv.height); //绘制圆 cxt.beginPath(); cxt.arc(x, 70, 20, 0, 360 * Math.PI / 180, true); cxt.closePath(); cxt.fillStyle = "#6699FF"; cxt.fill(); //变量递增 x += 2; })(); } </script>
</head>
<body>
<canvas id="canvas" width="200" height="150" style="border:1px solid silver;"></canvas>
</body>
</html>
边栏推荐
- 【jenkins】pipeline控制多job顺序执行,进行定时持续集成
- golang7_TCP编程
- MySQL数据库:使用show profile命令分析性能
- 喜迎市科协“十大”•致敬科技工作者 | 卢毅:守护电网传输安全的探索者
- Introduction to bloom filter
- [Jenkins] pipeline controls the sequential execution of multiple jobs for timed continuous integration
- 中康控股开启招股:拟募资净额3.95亿港元,预计7月12日上市
- 分布式唯一 ID 生成方案浅谈
- [shell] Jenkins shell realizes automatic deployment
- 28000 word summary of callable and future interview knowledge points. After reading it, I went directly to ByteDance. Forgive me for being a little floating (Part 2)
猜你喜欢

Application of ansvc reactive power compensation device in a shopping mall in Hebei

Nuscenes configuration information about radar

微信小程序:图片秒加水印制作生成

微信小程序:云开发表白墙微信小程序源码下载免服务器和域名支持流量主收益

Installation and removal of cover for CPU protection on desktop motherboard

golang6 反射

I talked about exception handling for more than half an hour during the interview yesterday

mysql函数和约束

喜迎市科协“十大”•致敬科技工作者 | 卢毅:守护电网传输安全的探索者

微信小程序:修复采集接口版云开发表情包
随机推荐
Kubernetes Pod 排错指南
单项数据流之子组件修改父组件的值
Are you still reading the log by command? Use kibana, one picture is better than ten thousand lines of log
Uncover the practice of Baidu intelligent test in the field of automatic test execution
一次mysql的.ibd文件过大处理过程记录
goby如何导出扫描结果
Wechat applet: new and exclusive cloud development wechat group contacts
Shell——文本处理命令
数字IC手撕代码--交通灯
《canvas》之第10章 canvas路径
How goby exports scan results
[dark horse morning post] the market value of China public education has evaporated by more than 200billion; New Oriental has more than 20million live fans; HM closes its first store in China; Vanke Y
"Dead" Nokia makes 150billion a year
[high concurrency] 28000 words' summary of callable and future interview knowledge points. After reading it, I went directly to ByteDance. Forgive me for being a little drifting (middle)
tcpdump如何对特定的tcp标志位进行过滤
微信小程序:全新独家云开发微群人脉
《canvas》之第6章 图片操作
微信小程序:万圣节头像框生成工具
Redis的数据过期清除策略 与 内存淘汰策略
Which is better and safer for Dongguan Humen securities company to open a stock account?