canvas实现跟随鼠标交互的龙卷风卷起小球动画效果代码

代码语言:html

所属分类:动画

代码描述:canvas实现跟随鼠标交互的龙卷风卷起小球动画效果代码

代码标签: canvas 跟随 鼠标 交互 龙卷风 卷起 小球 动画

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

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

<head>

  <meta charset="UTF-8">
  

  
  
<style>
body, html {
  height: 100%;
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: #e4e4e4;
}

canvas {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.floor {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0px;
  width: 100%;
  height: 30px;
  background: #457b9d;
  z-index: 3;
}
</style>



</head>

<body  >
  <canvas></canvas>
<div class="floor"></div>

      <script >
let h = window.innerHeight;
let w = window.innerWidth;
let time = 0;
let colors = ["#ffbe0b", "#fb5607", "#ff006e", "#8338ec", "#3a86ff"];
let gravity = 0.004;
let ctx = null;
let tornadoX = w / 2;
const bgColor = "#f1faee";

const e = 2.718;

class Ball {
  constructor(i) {
    this.weight = Math.random() * 20 + 10;
    this.r = this.weight;
    this.x = Math.random() * (w - this.r) + this.r / 2;
    this.y = 75;
    this.dy = 0;
    this.g = gravity * this.weight;
    this.dx = 0;
    this.color = colors[i % colors.length];
  }
  draw() {
    this.dy += this.g;

    this.dx += Math.abs(tornadoX - this.x) > 3 ? 1 / (tornadoX - this.x) : -0.01 * Math.sign(tornadoX - this.x);

    this.dy -= e ** -Math.abs((h - this.y) / 5000 * (tornadoX - this.x));

    if (this.y >= h - 30 - this.r) {
      this.y = h - 30 - this.r;
      this.dy = -this.dy / 2;
    }

    if (this.x < this.r || this.x + this.r > w) {
      this.dx = -this.dx;
    }
    if (this.y - this.r <= 0) {
      this.dy = -this.dy / 10;
    }
    this.y += this.dy;
    this.x += this.dx;
    if (this.y - this.r < 0) {
      this.y = this.r;
    }
    ctx.fillStyle = this.color;
    ctx.beginPath();
    ctx.arc(this.x, this.y, this.r, 0, 2 * Math.PI);
    ctx.fill();
  }}


class Balls {
  constructor() {
    this.count = 40;
    this.balls = [];
  }
  create() {
    for (let i = 0; i < this.count; i++) {
      this.balls.push(new Ball(i));
    }
  }
  draw() {
    this.balls.forEach(ball => {
      ball.draw();
    });
  }}

class Ellipse {
  constructor(y, w, i) {
    this.y = y;
    this.w = w;
    this.........完整代码请登录后点击上方下载按钮下载查看

网友评论0