html代码:

<body>
    <canvas id="canvas"></canvas>
</body>

css代码:

<style>
        body{
            margin: 100px;
        }
        #cavans{
            box-shadow: 0 0 10px #000;
        }
    </style>

js代码:

<script>
    // 1.处理画布
    const canvas=document.getElementById("canvas")
    const ctx=canvas.getContext('2d')
    canvas.width=800
    canvas.height=400
    canvas.style.backgroundColor='#000'
    // 2.创建小球类
    class Ball{
        constructor(x,y,color){
            this.x=x;
            this.y=y;
            this.color=color;
            this.r=40;
        }
        render(){
            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=Math.random()*(5-(-5))+(-5)
            this.dY=Math.random()*(5-(-5))+(-5)
            this.dR=Math.random()*(3-1)+(1)
        }
        update(){
            this.x+=this.dX
            this.y+=this.dY
            this.r-=this.dR
            if(this.r<0){
                this.r=0
            }
        }
    }
    // 3.实例化小球
    let ballArr=[]
    let colorArr=['red','green','blue','yellow','purple','pink','orange']
    // 4.监听鼠标移动
    canvas.addEventListener('mousemove',(e)=>{
        let moveBall=new MoveBall(e.offsetX,e.offsetY,colorArr[parseInt(Math.random()*(colorArr.length-1))])
        ballArr.push(moveBall)
    })
    // 5.开启定时器绘制
    setInterval(()=>{
        // 清屏
        ctx.clearRect(0,0,canvas.width,canvas.height)
        // 绘制
        for(let i=0,len=ballArr.length;i<len;i++){
            ballArr[i].render()
            ballArr[i].update()
        }
    },50)
</script>

效果图:
类的继承——cancas绘制五彩小球

相关文章:

  • 2021-07-30
  • 2022-12-23
  • 2022-12-23
  • 2022-02-01
  • 2022-12-23
  • 2021-10-23
  • 2021-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-10-06
  • 2022-12-23
  • 2022-01-27
  • 2022-12-23
  • 2021-12-01
相关资源
相似解决方案