当前位置:网站首页>《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>
边栏推荐
- Which is better and safer for Dongguan Humen securities company to open a stock account?
- VeeamBackup&Replication简介
- 【烹饪记录】--- 酸辣白菜
- MySQL数据库:存储引擎
- Uncover the practice of Baidu intelligent test in the field of automatic test execution
- How goby exports scan results
- ANSVC无功补偿装置在河北某购物广场中的应用
- 疯狂的数字藏品,下一个造富神话?
- 【VEUX开发者工具的使用-getters使用】
- 【jenkins】pipeline控制多job顺序执行,进行定时持续集成
猜你喜欢

Thinkpad VMware 安装虚拟机出现此主机支持 Intel VT-x,但 Intel VT-x 处于禁用状态(问题解决方法)

微信小程序:大红喜庆版UI猜灯谜又叫猜字谜

goby如何导出扫描结果

嵌入式开发:硬件在环测试

Wechat applet: install B artifact and P diagram, modify wechat traffic main applet source code, Download funny joke diagram, make server free domain name

Thanos Store 组件

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

节点数据采集和标签信息的远程洪泛传输

关于MongoDB报错:connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb

stm32 mbed 入门教程(四)---PWM
随机推荐
NuScenes关于Radar的配置信息
微信小程序:图片秒加水印制作生成
在同花顺上开户安全吗 开户在哪里申请
Interview high concurrent, cool!! (high energy in the whole process, collection recommended)
台式机主板上保护cpu的盖子安装和拆卸
文物数字藏品,开启文化传承的新方式
《canvas》之第12章 其他应用
[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 (Part 1)
Characteristics of human immaturity
leetcode:226. Flip binary tree
"Dead" Nokia makes 150billion a year
微信小程序:(更新)云开发微群人脉
Nuscenes configuration information about radar
《canvas》之第6章 图片操作
JUC多线程:线程池的创建及工作原理
Redis' data expiration clearing strategy and memory obsolescence strategy
MySQL数据库:drop、truncate、delete的区别
BYD has three years left
微信小程序:装B神器P图修改微信流量主小程序源码下载趣味恶搞图制作免服务器域名
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)