canvas实现鼠标悬浮排斥圈圈效果代码

代码语言:html

所属分类:悬停

代码描述:canvas实现鼠标悬浮排斥圈圈效果代码

代码标签: canvas 鼠标 悬浮 排斥 圈圈

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

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

<head>

  <meta charset="UTF-8">
  

  
  
  
<style>
* {
      padding: 0;
      margin: 0;
    }

    body {
      overflow: hidden;
      background: black;
    }
</style>




</head>

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

  
      <script>
const canvas = document.getElementById("can");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const ctx = canvas.getContext("2d");

const mouse = {
  x: null,
  y: null,
  radius: 150 };


canvas.onmousemove = e => {
  mouse.x = e.x;
  mouse.y = e.y;
};

//create ball object
class Ball {
  constructor(x, y, radius, color) {
    this.x = x;
    this.y = y;
    this.radius = radius;
    this.baseX = this.x;
    this.baseY = this.y;
    this.color = color;
    this.density = Math.random() * 30 + 1;
  }
  draw() {
    ctx.beginPath();
    ctx.arc(this.x, this.y, this.radius, 0, 2 * Math.PI);
    ctx.fillStyle = this.color;
    ctx.fill();
  }

  update() {
    let disX = mouse.x - this.x;
    let disY = mouse.y - this.y;

    //d or mag
    let distance = Math.sqrt(Math.pow(disX, 2) + Math.pow(disY, 2));

    //normalize r
    let dirX = disX / distance;
    let dirY = disY / distance;

    let friction = (mouse.radius - distance) / mouse.radius;

    let directio.........完整代码请登录后点击上方下载按钮下载查看

网友评论0