获得徽章 0
- 如何给canvas添加事件监听?
"要给`<canvas>`元素添加事件监听,可以使用JavaScript的`addEventListener`方法。以下是一个示例,展示如何为`canvas`添加鼠标点击和移动事件监听。
```html
<!DOCTYPE html>
<html lang=\"en\">
<head>
<meta charset=\"UTF-8\">
<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">
<title>Canvas Event Listener</title>
<style>
canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id=\"myCanvas\" width=\"500\" height=\"400\"></canvas>
<script>
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
// 鼠标点击事件
canvas.addEventListener('click', function(event) {
const rect = canvas.getBoundingClientRect(); // 获取canvas的边界
const x = event.clientX - rect.left; // 计算点击位置的X坐标
const y = event.clientY - rect.top; // 计算点击位置的Y坐标
// 在点击位置绘制圆圈
ctx.fillStyle = 'red';
ctx.beginPath();
ctx.arc(x, y, 10, 0,展开54 - 使用css3制作雪花效果
"```html
<!DOCTYPE html>
<html lang=\"en\">
<head>
<meta charset=\"UTF-8\">
<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">
<title>雪花效果</title>
<style>
body {
background-color: #282c34; /* 背景颜色 */
overflow: hidden; /* 隐藏滚动条 */
position: relative;
height: 100vh; /* 设置高度为视口高度 */
}
.snowflake {
position: absolute;
top: -10%; /* 从上方进入 */
color: #fff; /* 雪花颜色 */
font-size: 1em; /* 雪花大小 */
opacity: 0.8; /* 透明度 */
pointer-events: none; /* 不响应鼠标事件 */
animation: fall linear; /* 动画效果 */
}
@keyframes fall {
0% {
transform: translateY(0); /* 起始位置 */
}
100% {
transform: translateY(100vh); /* 结束位置 */
}
}
</style>
</head>
<body>
<script>
const createSnowflake = () => {
展开65
![[庆祝]](http://lf-web-assets.juejin.cn/obj/juejin-web/xitu_juejin_web/img/jj_emoji_123.da47506.png)
![[听歌]](http://lf-web-assets.juejin.cn/obj/juejin-web/xitu_juejin_web/img/jj_emoji_88.4eb52e4.png)
![[色]](http://lf-web-assets.juejin.cn/obj/juejin-web/xitu_juejin_web/img/jj_emoji_3.41d9a9a.png)
![[黑脸]](http://lf-web-assets.juejin.cn/obj/juejin-web/xitu_juejin_web/img/jj_emoji_99.3264111.png)