JavaScript实现液体流动效果和鼠标交互

这篇具有很好参考价值的文章主要介绍了JavaScript实现液体流动效果和鼠标交互。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

在现代Web应用中,动态效果和交互性已经成为了不可或缺的元素。在这篇博客中,我们将使用JavaScript创建一个液体流动效果,并添加鼠标交互功能,让用户能够与页面进行互动。

创建画布和粒子
首先,我们需要创建一个画布元素,用于绘制我们的液体流动效果。在HTML中添加以下代码:

<canvas id="canvas"></canvas>
接着,在JavaScript中获取该元素,并设置其大小与浏览器窗口相同:

const canvas = document.getElementById('canvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

接下来,我们需要创建液体粒子。在本例中,我们将使用一个Particle类来表示每个粒子。在类中,我们需要定义粒子的位置、大小、颜色和速度等属性。在这里,我们将定义随机速度和加速度,以使每个粒子的运动轨迹都不同。以下是Particle类的示例代码:

class Particle {
  constructor(x, y, size, color) {
    this.x = x;
    this.y = y;
    this.size = size;
    this.color = color;
    this.vx = Math.random() * 2 - 1;
    this.vy = Math.random() * 2 - 1;
    this.ax = 0;
    this.ay = 0;
  }

  update() {
    this.vx += this.ax;
    this.vy += this.ay;
    this.x += this.vx;
    this.y += this.vy;
  }

  draw(ctx) {
    ctx.fillStyle = this.color;
    ctx.beginPath();
    ctx.arc(this.x, this.y, this.size, 0, 2 * Math.PI);
    ctx.fill();
  }
}

接下来,我们需要创建一些粒子,并将它们存储在数组中。在本例中,我们将创建200个粒子,并将它们分布在画布的随机位置上。以下是示例代码:

const numParticles = 200;
const particles = [];

for (let i = 0; i < numParticles; i++) {
  const x = Math.random() * canvas.width;
  const y = Math.random() * canvas.height;
  const size = Math.random() * 10 + 5;
  const particleColor = `rgba(255, 255, 255, ${Math.random()})`;
  particles.push(new Particle(x, y, size, particleColor));
}

现在,我们已经创建了画布和粒子,并将它们存储在数组中。接下来,我们需要绘制它们。

绘制液体
在本例中,我们将使用canvas的渐变功能来绘制液体。我们将定义两种颜色,以在液体的顶部和底部之间创建渐变。以下是绘制液体的函数:

function drawLiquid() {
  const liquidWidth = canvas.width;
  const liquidHeight = 200;
  const liquidBottom = canvas.height - liquidHeight;
  const liquidColor1 = '#0A2463';
  const liquidColor2 = '#C0C0C0';

  const liquidGradient = ctx.createLinearGradient(0, liquidBottom, 0, canvas.height);
  liquidGradient.addColorStop(0, liquidColor1);
  liquidGradient.addColorStop(1, liquidColor2);

  ctx.fillStyle = liquidGradient;
  ctx.fillRect(0, liquidBottom, liquidWidth, liquidHeight);
}

在这里,我们定义了液体的宽度、高度和颜色,并使用createLinearGradient()方法创建了一个垂直渐变。最后,我们使用fillRect()方法绘制了液体矩形。

绘制粒子
现在,我们已经绘制了液体,接下来我们需要绘制粒子。我们将使用Particle类中定义的draw()方法来绘制每个粒子。以下是绘制粒子的函数:

function drawParticles() {
particles.forEach((particle) => {
particle.update();
particle.draw(ctx);
});
}

在这里,我们遍历粒子数组,并调用每个粒子的update()和draw()方法来更新和绘制它们的位置。

现在,我们已经实现了液体和粒子的绘制。接下来,我们将添加鼠标交互功能。

添加鼠标交互

在本例中,我们将创建一个鼠标粒子,它将跟随鼠标的移动而移动,并与其他粒子产生吸引力。以下是鼠标粒子的示例代码:

class MouseParticle extends Particle {
  constructor(x, y, size, color) {
    super(x, y, size, color);
    this.mass = 10;
  }

  update(mouseX, mouseY) {
    this.x = mouseX;
    this.y = mouseY;
  }

  attractionForce() {
    particles.forEach((particle) => {
      if (particle !== this) {
        const dx = particle.x - this.x;
        const dy = particle.y - this.y;
        const distance = Math.sqrt(dx * dx + dy * dy);
        const force = (this.mass * particle.mass) / (distance * distance);
        const ax = force * dx / distance;
        const ay = force * dy / distance;
        particle.ax -= ax;
        particle.ay -= ay;
      }
    });
  }
}

const mouseParticle = new MouseParticle(0, 0, 20, 'white');
在这里,我们继承了Particle类,并重写了update()方法,以便鼠标粒子可以跟随鼠标的移动而移动。我们还添加了一个attractionForce()方法,该方法将计算鼠标粒子和其他粒子之间的引力,并将其应用于其他粒子的加速度。

接下来,我们需要在动画循环中调用鼠标移动事件监听器和绘制鼠标粒子的方法。以下是动画循环的示例代码:

```javascript
let mouseX = canvas.width / 2;
let mouseY = canvas.height / 2;

canvas.addEventListener('mousemove', (event) => {
  mouseX = event.clientX;
  mouseY = event.clientY;
});

function loop() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  drawLiquid();
  drawParticles();
  mouseParticle.update(mouseX, mouseY);
  mouseParticle.attractionForce();
  mouseParticle.draw(ctx);
  requestAnimationFrame(loop);
}

loop();

在这里,我们添加了一个鼠标移动事件监听器,并在每次鼠标移动时更新鼠标的坐标。接下来,我们在动画循环中调用了绘制鼠标粒子的方法,并在每次循环中更新鼠标粒子的位置和其他粒子的加速度。

现在,我们已经实现了一个具有液体流动效果和鼠标交互的动态效果。您可以将下面的代码保存到文件,在浏览器打开查看效果。

总结
在本文中,我们使用JavaScript实现了一个液体流动效果和鼠标交互的动态效果。我们创建了画布和粒子,并使用canvas的渐变功能绘制了液体。我们还添加了鼠标粒子,并在每次循环中更新了粒子的位置和加速度。这个例子展示了JavaScript在动态效果和交互性方面的强大能力,希望对您有所帮助。

完整代码文章来源地址https://www.toymoban.com/news/detail-640188.html

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Liquid Flow Page</title>
  <style>
    body {
      background-color: #000;
      overflow: hidden;
    }

    canvas {
      position: absolute;
      top: 0;
      left: 0;
      z-index: -1;
    }

    h1 {
      font-size: 80px;
      color: #fff;
      text-align: center;
      margin-top: 200px;
    }
  </style>
</head>
<body>
  <h1>Liquid Flow Page</h1>
  <canvas id="canvas"></canvas>
  <script>
    // 创建canvas并设置大小
    const canvas = document.getElementById('canvas');
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;

    // 获取canvas上下文
    const ctx = canvas.getContext('2d');

    // 定义液体粒子的数量
    const numParticles = 200;

    // 定义液体粒子的颜色
    const particleColor = '#ff00ff';

    // 定义液体粒子的速度和加速度
    const particleSpeed = 2;
    const particleAcceleration = 0.05;

    // 定义液体的颜色
    const liquidColor1 = '#ff00ff';
    const liquidColor2 = '#00ffff';

    // 定义液体的高度和波动幅度
    const liquidHeight = 200;
    const liquidAmplitude = 50;

    // 定义鼠标粒子对象
    class MouseParticle {
      constructor(x, y, size, color) {
        this.x = x;
        this.y = y;
        this.size = size;
        this.color = color;
        this.vx = 0;
        this.vy = 0;
      }

      // 更新粒子的位置和速度
      update(x, y) {
        this.vx = (x - this.x) / 10;
        this.vy = (y - this.y) / 10;
        this.x += this.vx;
        this.y += this.vy;
      }

      // 绘制粒子
      draw() {
        ctx.fillStyle = this.color;
        ctx.beginPath();
        ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
        ctx.fill();
      }
    }

    // 创建鼠标粒子对象
    const mouseParticle = new MouseParticle(canvas.width / 2, canvas.height / 2, 20, particleColor);

    // 创建液体粒子对象
    class Particle {
      constructor(x, y, size, color) {
        this.x = x;
        this.y = y;
        this.size = size;
        this.color = color;
        this.vx = Math.random() * particleSpeed - particleSpeed / 2;
        this.vy = Math.random() * particleSpeed - particleSpeed / 2;
      }

      // 更新粒子的位置和速度
      update() {
        this.x += this.vx;
        this.y += this.vy;
        this.vy += particleAcceleration;
      }

      // 绘制粒子
      draw() {
        ctx.fillStyle = this.color;
        ctx.beginPath();
        ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
        ctx.fill();
      }

      // 计算粒子和鼠标粒子之间的距离
      distanceToMouse() {
        const dx = this.x - mouseParticle.x;
        const dy = this.y - mouseParticle.y;
        return Math.sqrt(dx * dx + dy * dy);
      }

      // 计算粒子和鼠标粒子之间的吸引力
      attractionForce() {
        const distance = this.distanceToMouse();
        const maxDistance = 100;
        const minDistance = 20;
        if (distance < maxDistance) {
          const force = (maxDistance - distance) / (maxDistance - minDistance);
          this.vx += (mouseParticle.vx * force) / 2;
          this.vy += (mouseParticle.vy * force) / 2;
        }
      }
    }

    // 创建液体粒子数组
    const particles = [];
    for (let i = 0; i < numParticles; i++) {
      const x = Math.random() * canvas.width;
      const y = Math.random() * canvas.height;
      const size= Math.random() * 10 + 5;
particles.push(new Particle(x, y, size, particleColor));
}

// 绘制液体
function drawLiquid() {
  const waveOffset = performance.now() / 1000;
  const liquidWidth = canvas.width;
  const liquidBottom = canvas.height - liquidHeight;

  const liquidGradient = ctx.createLinearGradient(0, liquidBottom, 0, canvas.height);
  liquidGradient.addColorStop(0, liquidColor1);
  liquidGradient.addColorStop(1, liquidColor2);

  ctx.fillStyle = liquidGradient;
  ctx.beginPath();
  ctx.moveTo(0, liquidBottom);
  for (let x = 0; x <= liquidWidth; x += 10) {
    const waveX = x / liquidWidth * Math.PI * 2;
    const waveY = Math.sin(waveX + waveOffset) * liquidAmplitude + liquidBottom;
    ctx.lineTo(x, waveY);
  }
  ctx.lineTo(canvas.width, canvas.height);
  ctx.lineTo(0, canvas.height);
  ctx.closePath();
  ctx.fill();
}

// 绘制粒子和鼠标粒子
function drawParticles() {
  particles.forEach((particle) => {
    particle.update();
    particle.attractionForce();
    particle.draw();
  });
  mouseParticle.update(mouseX, mouseY);
  mouseParticle.draw();
}

// 动画循环
let mouseX = canvas.width / 2;
let mouseY = canvas.height / 2;
canvas.addEventListener('mousemove', (event) => {
  mouseX = event.clientX;
  mouseY = event.clientY;
});

function loop() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  drawLiquid();
  drawParticles();
  requestAnimationFrame(loop);
}

loop();
</script> </body> </html>

到了这里,关于JavaScript实现液体流动效果和鼠标交互的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 【HTML+CSS+JavaScript】实现鼠标点击烟花效果

    本文主要讲解三种烟花效果(爆炸型、心型、圆形),文章末尾附有完整的代码和图片获取链接。 效果图(一) - 心型 : 效果图(二) - 圆型 : 效果图(三) - 爆炸型 : (1) HTML部分代码 (2) CSS部分代码 (3) 内部的JavaScript部分代码 (1) HTML部分代码 (2) CSS部分代码 (3) 内部的JavaScript部分

    2024年02月01日
    浏览(64)
  • UnityShader实现液体倾倒效果

    先看一下效果图  实现思路:在烧杯倾倒液体时,烧杯内的液体始终不会超过烧杯口的高度,所以我们计算得到这个高度值,然后截取掉超过该高度的像素 首先准备烧杯内液体的模型,挂载一下shader对应的材质球                                              shader部分

    2024年02月13日
    浏览(26)
  • Unity地面交互效果——2、动态法线贴图实现轨迹效果

    回到目录 Unity引擎动态法线贴图制作球滚动轨迹   大家好,我是阿赵。   之前说了一个使用局部UV采样来实现轨迹的方法。这一篇在之前的基础上,使用法线贴图进行凹凸轨迹的绘制。   先来回顾一下,上一篇最终我们已经绘制了一个轨迹的贴图   可以思考一下,

    2024年02月06日
    浏览(56)
  • 用js实现元素跟着鼠标转动效果

     当鼠标移入body时,元素跟着鼠标旋转,所有的元素都看向鼠标的位置。 在一个shell中,总共有 36 个item。 这里对shell盒子采用css3的网格布局,对它的子元素进行分成6行6列的形式,宽和高都为50px, 然后利用双伪元素来画它的小眼睛。 然后每个小方块都化成这个样子。 原理:

    2024年02月09日
    浏览(33)
  • JS创建DIV,实现鼠标拖拽效果

    题目:用原生js动态创建一个div,大小随意,挂在body上,实现鼠标拖拽效果 需要用到的鼠标事件: 1.鼠标按下(onmousedown), 2.鼠标移动(onmousemove) 3.鼠标抬起(onmouseup) 第一步:创建容器(每个页面,最大的容器是body对象,所有dom对象创建后默认都会放到body) 第二步,

    2024年02月13日
    浏览(35)
  • vue中通过JavaScript实现web端鼠标横向滑动&触控板滑动效果-demo

    JavaScript实现web端鼠标横向滑动触控板滑动效果  支持鼠标拖动滑动触控板滑动效果 web端实现滑动,就是对鼠标按下、鼠标松开、鼠标移动事件进行监听 在Vue中实现鼠标横向滑动触控板滑动效果可以通过以下步骤实现: 首先在Vue中创建一个父组件,在该组件中引入子组件或者

    2024年02月15日
    浏览(26)
  • 【JavaScript】原生js实现省市区联动效果

    😉博主:初映CY的前说(前端领域) ,📒本文核心:用原生js实现省市区联动 【前言】今日在复习省市县三级联动的时候,有点忘了原生的js应该怎么样处理省市县的联动,特此写下来再次复习下 1.获取相对应的DOM对象 2.写省市县接口获取到接口信息 3.写下change事件,有变化时调

    2023年04月24日
    浏览(39)
  • three.js实现鼠标点击控制物体移动(带动画效果,位置精确)

    通过查阅各种资料,最终确定解决方案,动画效果使用gsap组件库实现,也可不用,代码稍作修改即可。解决鼠标点击坐标偏移问题,复制可直接运行。 完整代码如下:

    2024年02月07日
    浏览(43)
  • 使用css实现边框流动效果

    要实现一个边框流动的效果,可以使用CSS动画来实现。在HTML中,我们需要创建一个元素(例如div),并将其设置为具有一定宽度和高度的盒子。然后,我们可以使用CSS来定义该元素的边框样式、位置和动画。 首先,我们需要在CSS中定义我们的元素。我们可以设置该元素的宽

    2024年02月09日
    浏览(35)
  • ArcGIS API for JavaScript 4.x 实现动态脉冲效果

    主要通过定时刷新,每一次的脉冲渲染圈不停的放大,并且透明度缩小,直到达到一定的大小再退回0。 这个文件拿去可以直接使用,下面是引入的方式: 然后可以调用提供的方法实现动态点的添加,动画的暂停和启动。

    2024年02月09日
    浏览(33)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包