JavaScript canvas实现跟随鼠标移动小球
编程学习 2021-07-04 14:07www.dzhlxh.cn编程入门
这篇文章主要为大家详细介绍了JavaScript canvas实现跟随鼠标移动小球,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
本文实例为大家分享了js跟随鼠标移动小球的具体代码,供大家参考,具体内容如下
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
canvas{
border: 1px solid #000;
}
</style>
</head>
<body>
<canvas id="mycanvas" width="1500" height="800"></canvas>
<script>
// 创建画布
var canvas = document.getElementById('mycanvas');
var ctx = canvas.getContext('2d');
// 球类
function Ball(x, y) {
this.x = x;
this.y = y;
// 初始半径
this.r = parseInt(Math.random() * 50) + 10;
this.step = parseInt(Math.random() * 5) + 0.1;
// 设置随机颜色
this.color = getRandom();
// 设置随机方向
this.dx = parseInt(Math.random() * 10) - 5;
this.dy = parseInt(Math.random() * 10) - 5;
// 将自身对象装入数组中
ballArr.push(this);
}
// 在数组中删除对象
Ball.prototype.remove = function() {
for (var i = 0; i < ballArr.length; i++) {
if (ballArr[i] == this) {
ballArr.splice(i, 1);
}
}
}
// 更新数据
Ball.prototype.update = function() {
// 更新数据
this.x += this.dx;
this.y += this.dy;
this.r -= this.step;
// 清除数组中的小球
if (this.r <= 0) {
this.remove();
}
// 如果超出边界,小球继续运动
if (this.x < 0) {
this.x = 1500;
this.color = getRandom();
}
else if (this.x > 1500) {
this.x = 0;
this.color = getRandom();
}
else if (this.y < 0) {
this.y = 800;
this.color = getRandom();
}
else if (this.y > 800) {
this.y = 0;
this.color = getRandom();
}
}
// 渲染小球
Ball.prototype.render = function() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2, false);
ctx.fillStyle = this.color;
ctx.fill();
}
// canvas 画布DOM2事件
canvas.addEventListener("mousemove", function(event) {
new Ball(event.offsetX, event.offsetY);
});
var ballArr = [];
// 定时器进行动画渲染和更新
setInterval(function() {
// 动画逻辑
// 清屏-更新-渲染
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 小球的更新和渲染
for (var i = 0; i < ballArr.length; i++) {
ballArr[i].update();
if (ballArr[i]) {
ballArr[i].render();
}
}
}, 30);
// 随机颜色
function getRandom() {
var allType = "0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f";
var allTypeArr = allType.split(",");
var color = "#";
// 拼接颜色字符串
for (var i = 0; i < 6; i++) {
var random = parseInt(Math.random() * allTypeArr.length);
color += allTypeArr[random];
}
return color;
}
</script>
</body>
</html>
效果
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持狼蚁SEO。
编程语言
- ThinkPad 笔记本如何调节LCD屏幕亮度
- Dreamweaver制作网页打开特效教程
- Win10 Mobile 10586升级后无限重启怎么办 硬重启帮您
- Win8系统提示音频设备有问题有一个或多个音频服
- Xbox One版Win10首个预览版9月份发布
- 如何在textarea文本输入区内实现换行
- Win10 Build 9901系统更新 预览版新版本下载
- McAfee Framework存在远程格式串处理漏洞
- Win10家庭版今日(7月30)正式在中国官方商城开卖
- Win10 Mobile预览版更新完10536.1000后才收到10536.100
- Win10 RS2更新了什么-Win10 RS2最终版本号1704首曝
- Windows7如何查看回收站对应的文件夹有哪些方法
- Win10让Charms栏回归桌面的方法教程
- 取消Windows XP系统开机启动画面的小技巧
- win8系统怎么下载安装USB百兆网卡?
- XP系统下磁盘空间变少了怎么办?XP系统磁盘空间