Canvas_鼠标移动炫彩小球

solokeke 2017-04-06 07:05:42
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>canvas</title>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
img{
border:0;
}
ol, ul ,li{list-style: none;}
canvas{
border: 1px solid #000;
}
</style>
</head>
<body>
<canvas id="mycanvas" width="1000" height="600"></canvas>
<script type="text/javascript">

var mycanvas = document.getElementById("mycanvas");
var ctx = mycanvas.getContext("2d");
//圆形类
function Circle(x,y,r,color){
this.x = x;
this.y = y;
this.r = r;
// 颜色的取值范围
this.color = "rgb("+ (parseInt(Math.random() * 240 ) + 9) + ","+ (parseInt(Math.random() * 220 )+18) +",203)";

//随机方向
this.dx = Math.random() * 12 - 7;
this.dy = Math.random() * 12 - 7;
//往数组中push自己
circleArr.push(this);
}

//渲染
Circle.prototype.render = function(){
//新建一条路径
ctx.beginPath();
//创建一个圆
ctx.arc(this.x, this.y, this.r, 0, Math.PI*2, true);
//设置样式颜色
ctx.fillStyle = this.color;
//通过填充路径的内容区域生成实心的图形
ctx.fill();
}
更多资料免费分享加群 120342833 验证回答 ZZ
//更新
Circle.prototype.update = function(){
this.x += this.dx;
this.y += this.dy;
this.r--;
if(this.r < 0){
for (var i = 0; i < circleArr.length; i++) {
if (circleArr[i] === this) {
circleArr.splice(i,1);
};
}
return false;
}
return true;
}
//创建一个数组
var circleArr = [];

//鼠标移动事件
mycanvas.onmousemove = function(event){
new Circle(event.clientX,event.clientY,30,"orange");
}

//设置定时器每20毫秒更新和渲染
setInterval(function(){
ctx.clearRect(0, 0, 1000, 600)
for (var i = 0; i < circleArr.length; i++) {
circleArr[i].update() && circleArr[i].render();
};
},20);


</script>
</body>
</html>
...全文
194 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

2,100

社区成员

发帖
与我相关
我的任务
社区描述
Web 开发 非技术区
社区管理员
  • 非技术区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧