es6绚丽小球案例以及canvas设置width和height的问题

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/baidu_39067385/article/details/84838703

本例的实现思路如下:
 1.首先创建画布,定义画布的样式,创建画布的上下文对象;
 2.一个个的小球是一个对象,所以需要创建一个球类,定义球的基本属性
 3.创建会移动的小球的类,继承球类,在这个类中继承球类的基本属性,
   同时可以可以定义新的行为和属性;比如所有移动的变化的量,半径的
   变化量;
 4.而这些变量随机取得的效果则需要underscore.js(插件,百度下载一下就有)才提供,这
   时javascript的一个工具库,我们引入之后,通过_.random()来取得
   随机变量;

  对于随机数的取得,除了引入第三方插件,还可以自己自定义随机函数,取得随机数

    //封装Math.random()函数,在需要取得随机数的位置调用该函数即可
    function MyRandom(n, m) {
        //取n到m的随机数, [n, m]
        return Math.round(Math.random()*(m-n)+n);
    }

5.监听鼠标事件,获取鼠标移动位置,在鼠标移动的位置创建对应的移动小球
 对象,把这些对象存进数组中保存,再定义定时器来绘制和移动数组中的小球

实现代码如下:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>绚丽小球</title>
        <style type="text/css">
        body{
            margin: 150px;
        }
         #canvas{
/*          	在这里设置canvas的宽度和高度会导致canvas被拉伸,
         	使得绘图位置发生偏移 */
/*          	width: 1000px;
         	height: 600px;
         	background-color: #000; */
         	box-shadow: 0 0 10px #000;
         }
        </style>
    </head>
    <body>
    <canvas id="canvas">浏览器版本多低,请更新!</canvas>
<!--     引入underscore.js这是javascript的工具类在本例中可以提供小球
    移动的随机数和在颜色数组中取得随机颜色 -->
    <script src="underscore.js"></script>
    <script type="text/javascript">
     let canvas=document.getElementById("canvas");
     const ctx=canvas.getContext("2d");
     canvas.width = 1000;
     canvas.height = 600;
     canvas.style.backgroundColor = '#000';
     //小球类
     class Ball{
     	constructor(x,y,color){
          this.x=x;
          this.y=y;
          this.color=color;
          this.r=40;
     	}
     	//绘制小球
     	drawBall(){
           ctx.save();
           ctx.beginPath();
           ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2);
           ctx.fillStyle = this.color;
           ctx.fill();
           ctx.restore();

     	}
     }
         /**
     * 会移动的小球类
     * */
    class MoveBall extends Ball {
        constructor(x ,y, color){
            super(x ,y, color);
            //量的变化
            this.dX = _.random(-5,5);
            this.dY = _.random(-5,5);
            this.dR = _.random(1,3);
        }
        /**更新移动 */
        upDate(){
            this.x +=this.dX;
            this.y += this.dY;
            this.r -= this.dR;
            if(this.r<0){
                this.r =0;
            }
 
        }
    }

        let ballarray=[];
        let colors=['red','orange','green','pink','blue','yellow','purple'];

        //监听鼠标在canvas控件中的移动
        canvas.addEventListener('mousemove',function(e){
        	let rancolor=_.random(0,colors.length-1);
        	ballarray.push(new MoveBall(e.offsetX,e.offsetY,colors[rancolor]));
        	console.log(ballarray);
        });
        canvas.addEventListener('mouseout', function(e){
            setTimeout(function(){
             ballarray=[];
            }, 2000)
        });
        //开启定时器
        setInterval(function(){
        	// 每次更新重新绘制小球时要清屏
        	ctx.clearRect(0, 0, canvas.width, canvas.height);
        	// 如果小球个数大于1000就重置数组,保证性能
        	if(ballarray.length>1000) ballarray=[];
        	// 遍历数组绘制小球
        	for(let i=0;i<ballarray.length;i++){
                ballarray[i].drawBall();
                ballarray[i].upDate();
        	}
        }, 50);
    </script>
    </body>
</html>

 实现效果:

在实现的过程中发现对于canvas的宽度和高度如果设置不正确的话会导致运行结果中,小球的图像和移动会被拉伸,

运行结果变成如下所示:

canvas的默认宽度和高度是300*150,canvas相当于一个放着画纸的画板,当画板和画纸的宽度和高度相等时,

那么在canvas画出的图像就不会被拉伸,如果不相等那么图像就会被拉伸;

width和height属性设置的是画板和画布的宽度和高度;

//不会被拉伸的写法有两种:
//方法一:
<canvas id="myCanvas" width="200" height="200" style="border:1px solid black;">
    Your browser does not support the canvas element.
</canvas>

//方法二

     let canvas=document.getElementById("canvas");
     const ctx=canvas.getContext("2d");
     canvas.width = 1000;
     canvas.height = 600;
     canvas.style.backgroundColor = '#000';

猜你喜欢

转载自blog.csdn.net/baidu_39067385/article/details/84838703
今日推荐