canvas实现可调参数多彩小球碰撞带拖影动画效果代码

代码语言:html

所属分类:动画

代码描述:canvas实现可调参数多彩小球碰撞带拖影动画效果代码

代码标签: canvas 调参数 多彩 小球 碰撞 拖影 动画

下面为部分代码预览,完整代码请点击下载或在bfwstudio webide中打开

<!DOCTYPE html>
<html lang="en" >

<head>

  <meta charset="UTF-8">
  

  
  
  
<style>
* {
  box-sizing: border-box;
}

body {
  padding: 0;
  margin: 0;
  overflow: hidden;
  background-color: #111;
}

#range-cont {
  position: absolute;
  top: 1rem;
  left: 1rem;
  z-index: 99999;
  color: #fff;
}
#range-cont label {
  display: block;
}
</style>



</head>

<body>
  <canvas id="main-canvas"></canvas>
<div id="range-cont">
  <input id="num-of-balls" name="num-of-balls" type="range" value="20" min="4" max="80">
  <label id="range-label" for="num-of-balls">Balls: </label>
  <input id="size-of-balls" name="size-of-balls" type="range" value="20" min="5" max="75">
  <label id="size-label" for="size-of-balls">Size: </label>
</div>

  
      <script >
console.clear();

addEventListener('DOMContentLoaded', () => {
  const canvas = document.querySelector('#main-canvas');
  const c = canvas.getContext('2d');

  canvas.width = innerWidth;
  canvas.height = innerHeight;

  let balls = [];

  class Ball {
    constructor(x, y, size, xVel, yVel, density, hue) {
      this.x = x;
      this.y = y;
      this.size = size;
      this.xVel = xVel;
      this.yVel = yVel;
      this.density = density;
      this.hue = hue;
    }
    update() {
      this.x += this.xVel;
      this.y += this.yVel;

      // if hits border
      if (this.x + this.size >= canvas.width || this.x - this.size <= 0) {
        this.xVel *= -1;
      }
      if (this.y + this.size >= canvas.height || this.y - this.size <= 0) {
        this.yVel *= -1;
      }

    }
    draw() {
      c.beginPath();
      c.fillStyle = `hsl(${this.hue}, 65%, 65%)`;
      c.arc(this.x, this.y, this.size, 0, Math.PI * 2);
      c.fill();
      c.closePath();
    }}


  const init = num => {
    document.querySelector('#range-label').textContent = `Balls: ${num}`;
    document.querySelector('#size-label').textContent = `Size: ${20}`;.........完整代码请登录后点击上方下载按钮下载查看

网友评论0