html,,,,,Canvas 鼠标与键盘事件示例,, canvas {, border: 1px solid black;, },,,,,, const canvas = document.getElementById('myCanvas');, const ctx = canvas.getContext('2d');,, canvas.addEventListener('mousedown', (e) => {, ctx.beginPath();, ctx.arc(e.clientX, e.clientY, 5, 0, 2 * Math.PI);, ctx.fill();, });,, canvas.addEventListener('keydown', (e) => {, if (e.key === 'ArrowUp') {, ctx.clearRect(0, 0, canvas.width, canvas.height);, }, });,,,,
``,,在这个示例中,我们创建了一个 HTML5 Canvas,并为其添加了鼠标按下(mousedown)和键盘按下(keydown)事件监听器。当用户在 Canvas 上按下鼠标时,会在鼠标位置画一个圆形;当用户按下向上箭头键时,会清除 Canvas 上的所有内容。HTML5 Canvas鼠标与键盘事件demo示例
HTML5 Canvas是一个强大的工具,可以用于绘制图形、动画和游戏,在开发过程中,处理用户的输入是至关重要的,这包括鼠标和键盘事件的处理,本文将通过一个示例展示如何在Canvas上处理这些事件,并实现一个简单的交互功能。
获取Canvas对象上的鼠标坐标
Canvas支持所有的JavaScript鼠标事件,包括鼠标点击、按下、抬起和移动,为了处理这些事件,可以通过API或者反模式(inline event handler)来添加事件监听器。
1、通过API添加事件监听器:
```javascript
canvas.addEventListener("mousedown", doMouseDown, false);
canvas.addEventListener('mousemove', doMouseMove, false);
canvas.addEventListener('mouseup', doMouseUp, false);
```
2、通过反模式添加事件监听器:
```javascript
canvas.onmousedown = function(e){};
canvas.onmouseup = function(e){};
canvas.onmousemove = function(e){};
```
由于Canvas上的鼠标事件不能直接获取鼠标在Canvas上的坐标,需要通过以下方法计算:
function getPointOnCanvas(canvas, x, y) { var bbox = canvas.getBoundingClientRect(); return { x: x bbox.left * (canvas.width / bbox.width), y: y bbox.top * (canvas.height / bbox.height) }; }
键盘事件处理
HTML5 Canvas本身不支持键盘事件监听与获取,常用的有两种方法来解决这个问题:
1、通过window对象实现Canvas键盘事件监听与处理:
```javascript
window.addEventListener('keydown', doKeyDown, true);
```
2、通过在Canvas对象上添加其他支持键盘事件的DOM元素实现键盘事件支持:
```html
<canvas id="event_canvas" tabindex="0"></canvas>
```
```javascript
canvas.addEventListener('keydown', doKeyDown, true);
canvas.focus();
```
下面是一个根据键盘上下左右移动矩形块的完整示例代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF8"> <meta name="viewport" content="width=devicewidth, initialscale=1.0"> <title>Canvas Mouse and Keyboard Events</title> </head> <body> <canvas id="event_canvas" width="600" height="400" tabindex="0"></canvas> <script> var tempContext = null; // global variable 2d context var started = false; var mText_canvas = null; var x = 0, y = 0; window.onload = function() { var canvas = document.getElementById("event_canvas"); canvas.width = canvas.parentNode.clientWidth; canvas.height = canvas.parentNode.clientHeight; if (!canvas.getContext) { console.log("Canvas not supported. Please install a HTML5 compatible browser."); return; } // get 2D context of canvas and draw rectangle tempContext = canvas.getContext("2d"); tempContext.fillStyle = "blue"; x = canvas.width / 2; y = canvas.height / 2; tempContext.fillRect(x, y, 80, 40); // key event use DOM element as object canvas.addEventListener('keydown', doKeyDown, true); canvas.focus(); // key event use window as object window.addEventListener('keydown', doKeyDown, true); // mouse event canvas.addEventListener("mousedown", doMouseDown, false); canvas.addEventListener('mousemove', doMouseMove, false); canvas.addEventListener('mouseup', doMouseUp, false); } function getPointOnCanvas(canvas, x, y) { var bbox = canvas.getBoundingClientRect(); return { x: x bbox.left * (canvas.width / bbox.width), y: y bbox.top * (canvas.height / bbox.height) }; } function doKeyDown(e) { var keyID = e.keyCode ? e.keyCode : e.which; if (keyID === 38 || keyID === 87) { // up arrow and W clearCanvas(); y = y 10; tempContext.fillRect(x, y, 80, 40); e.preventDefault(); } if (keyID === 39 || keyID === 68) { // right arrow and D clearCanvas(); x = x + 10; tempContext.fillRect(x, y, 80, 40); e.preventDefault(); } if (keyID === 40 || keyID === 83) { // down arrow and S clearCanvas(); y = y + 10; tempContext.fillRect(x, y, 80, 40); e.preventDefault(); } if (keyID === 37 || keyID === 65) { // left arrow and A clearCanvas(); x = x 10; tempContext.fillRect(x, y, 80, 40); e.preventDefault(); } } function clearCanvas() { tempContext.clearRect(0, 0, tempContext.canvas.width, tempContext.canvas.height); } </script> </body> </html>
FAQs
Q1: 如何在Canvas中获取鼠标的坐标?
A1: 在Canvas中,鼠标事件不能直接获取鼠标在Canvas上的坐标,只能获取基于整个屏幕的坐标,需要通过e.pageX
和e.pageY
获取鼠标的位置,然后通过Canvas.getBoundingClientRect()
方法获取Canvas对象相对于屏幕的位置,通过计算得到鼠标在Canvas上的坐标,具体代码如下:
function getPointOnCanvas(canvas, x, y) { var bbox = canvas.getBoundingClientRect(); return { x: x bbox.left * (canvas.width / bbox.width), y: y bbox.top * (canvas.height / bbox.height) }; }
Q2: HTML5 Canvas如何实现键盘事件监听?
A2: HTML5 Canvas本身不支持键盘事件监听与获取,可以通过两种方法来实现:一是通过window
对象实现键盘事件监听;二是通过在Canvas对象上添加支持键盘事件的DOM元素(例如设置tabindex
属性),然后对该DOM元素进行事件监听,具体代码如下:
<canvas id="event_canvas" tabindex="0"></canvas>
canvas.addEventListener('keydown', doKeyDown, true); canvas.focus();
# HTML5 Canvas 鼠标与键盘事件 Demo 示例
在这个示例中,我们将创建一个简单的 HTML5 Canvas 应用程序,它能够响应鼠标和键盘事件,我们将实现以下功能:
鼠标点击位置显示坐标
鼠标拖动绘制线条
键盘按键切换绘制线条的颜色
### HTML 部分
```html
```
### JavaScript 部分 (script.js)
```javascript
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
let isDrawing = false;
let lastX = 0;
let lastY = 0;
let color = 'black';
canvas.addEventListener('mousedown', function(e) {
isDrawing = true;
lastX = e.clientX canvas.offsetLeft;
lastY = e.clientY canvas.offsetTop;
});
canvas.addEventListener('mousemove', function(e) {
if (isDrawing) {
const currentX = e.clientX canvas.offsetLeft;
const currentY = e.clientY canvas.offsetTop;
ctx.beginPath();
ctx.moveTo(lastX, lastY);
ctx.lineTo(currentX, currentY);
ctx.strokeStyle = color;
ctx.stroke();
lastX = currentX;
lastY = currentY;
}
});
canvas.addEventListener('mouseup', function() {
isDrawing = false;
});
canvas.addEventListener('mouseout', function() {
isDrawing = false;
});
document.addEventListener('keydown', function(e) {
if (e.key === 'c') {
color = 'black';
} else if (e.key === 'm') {
color = 'red';
} else if (e.key === 'y') {
color = 'green';
}
});
canvas.addEventListener('click', function(e) {
const x = e.clientX canvas.offsetLeft;
const y = e.clientY canvas.offsetTop;
ctx.fillText(`(${x}, ${y})`, x, y);
});
```
### 说明
1. **HTML 结构**:定义了一个 `canvas` 元素和一个 `script` 元素来包含 JavaScript 代码。
2. **CSS 样式**:为 `canvas` 元素添加了边框,以便于查看绘制区域。
3. **JavaScript 代码**:
为 `canvas` 添加了 `mousedown`、`mousemove`、`mouseup` 和 `mouseout` 事件监听器,以实现鼠标拖动绘制线条的功能。
`mousedown` 事件启动绘制,并记录初始坐标。
`mousemove` 事件在鼠标移动时绘制线条,并更新最后一个点的坐标。
`mouseup` 和 `mouseout` 事件停止绘制。
为文档添加了 `keydown` 事件监听器,以改变线条颜色。
为 `canvas` 添加了 `click` 事件监听器,以在鼠标点击位置显示坐标。
通过运行此示例,你可以看到鼠标拖动绘制线条的效果,并且可以通过键盘上的 'c'、'm' 和 'y' 键来切换线条颜色。