js实现canvas橙色方块滑动背景动画效果代码

代码语言:html

所属分类:背景

代码描述:js实现canvas橙色方块滑动背景动画效果代码

代码标签: 橙色 方块 滑动 背景 动画 效果

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

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


</head>
<body>

<canvas></canvas>

<script >
    console.clear();

const canvas = document.querySelector("canvas");
const context = canvas.getContext("2d");
canvas.height = window.innerHeight * 2;
canvas.width = window.innerWidth * 2;

const deg = 13;
const thetaA = Math.PI * (360 - deg) / 180.0;
const thetaB = Math.PI * deg / 180.0;
const cosA = Math.cos(thetaA);
const sinA = Math.sin(thetaA);
const cosB = Math.cos(thetaB);
const sinB = Math.sin(thetaB);

class Pane {
  constructor() {
    this.direction = Streak.generateDirection();
    this.speed = Streak.generateSpeed();
    this.radiusA = Streak.generateRadius();
    this.radiusB = Streak.generateRadius();
    this.y1 = Streak.generateY();
    this.x1 = this.direction === 1 ? -canvas.width : canvas.width;
    this.cosA = this.direction === 1 ? cosA : cosB;
    this.sinA = this.direction === 1 ? sinA : sinB;
    this.cosB = this.direction === 1 ? cosB : cosA;
    this.sinB = this.direction === 1 ? sinB : sinA;
  }

  tick() {
    const cos = this.speed * this.cosA;
    const sin = this.speed * this.sinA;
    this.x1 = this.x1 + (this.direction * cos);
    this.y1 = this.y1 + (this.direction * sin);
    this.x2 = this.x1 + this.radiusA * this.cosA;
    this.y2 = this.y1 + this.radiusA * this.sinA;
    this.x3 = this.x1 + this.radiusB * this.cosB;
    this.y3 = this.y1 + this.radiusB * this.sinB;
    this.x4 = this.x2 + this.radiusB * this.cosB;
    this.y4 = this.y2 + this.radiusB * this.sinB;
    this.speed = Math.pow(this.speed, 1.0025);
    return this.isOffscreen();
  }
  
  isOffscreen() {
    if (this.direction === 1) {
      return this.y3 < 0 || this.x1 > canvas.width;
    } else {
      return this.y2 < 0 || this.x4 < 0; 
    }
  }

  static generateDirection() {
    return Math.random() > 0.5 ? 1 : -1;
  }
  
  static generateRadius() {
    const factor = canvas.width * 1;
    return Math.round(Math.random() * factor * 0.75 + factor * 0.25);
  }

  static generateSpeed() {
    return Math.round(Math.random() * 10 + 10);
  }
  
  static generateY() {
    return Math.round(Math.random() * canvas.height * 2);
  }
}

class Streak {
  constructor() {
    this.direction = Streak.generateDirection();
    this.speed = Streak.generateSpeed();
    this.radius = Streak.generateRadius();
    this.y1 = Streak.generateY();
    this.x1 = this.direction === 1 ? -this.radius : canvas.width;
    this.cos = this.direction === 1 ? cosA : cosB;
    this.sin = this.direction === 1 ? sinA : sinB;
  }

  tick() {
    const cos = this.speed * this.cos;
    const sin = this.speed * this.sin;
    this.x1 = this.x1 + (this.direction * cos);
    this.y1 = this.y1 + (this.direction * sin);
    this.x2 = this.x1 + this.radius * this.cos;
    this.y2 = this.y1.........完整代码请登录后点击上方下载按钮下载查看

网友评论0