<!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)";
?
????????????//隨機(jī)方向
????????????this.dx = Math.random() * 12 - 7;
????????????this.dy = Math.random() * 12 - 7;
????????????//往數(shù)組中push自己
????????????circleArr.push(this);
?????????}
?
?????????//渲染
?????????Circle.prototype.render = function(){
????????????//新建一條路徑
????????????ctx.beginPath();
????????????//創(chuàng)建一個(gè)圓
????????????ctx.arc(this.x, this.y, this.r, 0, Math.PI*2, true);
????????????//設(shè)置樣式顏色
????????????ctx.fillStyle = this.color;
????????????//通過填充路徑的內(nèi)容區(qū)域生成實(shí)心的圖形
????????????ctx.fill();
?????????}
?
?????????//更新
?????????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;
?????????}
?????????//創(chuàng)建一個(gè)數(shù)組
?????????var circleArr = [];
?
?????????//鼠標(biāo)移動(dòng)事件
?????????mycanvas.onmousemove = function(event){
????????????new Circle(event.clientX,event.clientY,30,"orange");
?????????}
?
?????????//設(shè)置定時(shí)器每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>
感興趣的朋友可以加我好友一起討論