华域联盟 JavaScript 教你用几十行js实现很炫的canvas交互特效

教你用几十行js实现很炫的canvas交互特效

目录

废话不多说,先上效果图!

本篇文章的示例代码都是抄的一个叫Franks的老外在yutube上的一个教学视频,他还出了很多关于canvas的视频,十分值得学习,而我对canvas也不太熟悉,跟着大神一起敲代码,做个学习笔记,还要说一下,本文示例的页面结构很简单(html只包含一个canvas),后面代码部分就不贴了,毕竟js才是主角。

1.画圆

首先从画一个静态的圆开始吧,只需要了解很少的API即可,MDN上有详细的描述,这里就不过多介绍了,直接看js代码吧:

const canvas = document.querySelector('#canvas');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
function drawCircle() {
 ctx.beginPath();
 ctx.fillStyle = 'blue';
 ctx.arc(10, 10, 10, 0, Math.PI * 2);
 ctx.fill();
 ctx.closePath();
}
drawCircle();

现在一个半径为10px的圆就画出来了,即便是没有接触过canvas的人也能短时间画出来,很简单吧,接下来在这个基础上再加些动画吧。

2.鼠标移动的圆

现在想让圆随着鼠标移动,那么需要在canvas上绑定鼠标交互事件,这里我们就关注mousemove/click事件,随着鼠标的移动圆的坐标也发生了变化,因此需要更新圆的坐标,至于动画就通过requestAnimationFrame来实现,代码稍微多了一点点:

const mouse = {};
canvas.addEventListener('mousemove', (e) => {
 mouse.x = e.x;
 mouse.y = e.y;
});
canvas.addEventListener('click', (e) => {
 mouse.x = e.x;
 mouse.y = e.y;
});
canvas.addEventListener('mouseout', () => {
 mouse.x = mouse.y = undefined;
});
function drawCircle() {
 ctx.beginPath();
 ctx.fillStyle = 'blue';
 ctx.arc(mouse.x, mouse.y, 10, 0, Math.PI * 2);
 ctx.fill();
 ctx.closePath();
}
function animate() {
 ctx.clearRect(0, 0, canvas.width, canvas.height);
 drawCircle();
 requestAnimationFrame(animate);
}
animate();

效果如下,小球就能随着鼠标移动了,很简单吧。

如果把animate函数中ctx.clearRect注释掉,那么效果就像这样子:

3.鼠标拖动的粒子

粒子呢也就是很多圆,位置、大小、速率不同,再结合鼠标事件对象信息进行粒子的初始化就可以啦。

const mouse = {};
// 点击或鼠标移动时往数组添加新的粒子对象
function addNewParticles(e) {
 mouse.x = e.x;
 mouse.y = e.y;
 Array.apply(null, { length: 2 }).forEach(() => {
  particlesArray.push(new Particle());
 });
}
canvas.addEventListener('mousemove', addNewParticles);
canvas.addEventListener('click', addNewParticles);
const particlesArray = [];
class Particle {
 constructor() {
  this.x = mouse.x;
  this.y = mouse.y;
  this.size = Math.random() * 5 + 1;
  this.speedX = Math.random() * 3 - 1.5; // -1.5 ~ 1.5,如果是负数往左边移动,正数往右边移动,speedY同理
  this.speedY = Math.random() * 3 - 1.5;
 }
 update() {
  this.size -= 0.1; // 圆半径逐渐变小
  this.x += this.speedX; // 更新圆坐标
  this.y += this.speedY;
 }
 draw() {
  ctx.beginPath();
  ctx.fillStyle = '#fff';
  ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
  ctx.fill();
  ctx.closePath();
 }
}
function handleParticles() {
 for (let i = 0; i < particlesArray.length; i++) {
  particlesArray[i].update();
  particlesArray[i].draw();
  if (particlesArray[i].size <= 0.3) { // 删除半径太小的粒子
   particlesArray.splice(i, 1);
   i--;
  }
 }
}
function animate() {
 handleParticles();
 requestAnimationFrame(animate);
}
animate();

现在就实现了文章开头的第一幅动画效果,这里我们主要新增了一个Particle类来封装粒子的更新与绘制,然后根据条件删除较小的粒子,到这里也还是很简单吧,代码也就几十行,但是效果还不错。

4.颜色渐变的粒子

要实现颜色渐变,视频作者使用了hsl颜色模型,和我们熟知的rgb模式相比,通过一个变量就可以控制颜色了,十分方便,那么在第三段代码片段的基础上稍微改一下即可:

let hue = 0; // 色相
......
class Particle {
 ......
 draw() {
  ctx.beginPath();
  ctx.fillStyle = `hsl(${hue}, 100%, 50%)`;
  ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
  ctx.fill();
  ctx.closePath();
 }
}
function handleParticles() {
 ......
}
function animate() {
    hue++;
    handleParticles();
    requestAnimationFrame(animate);
 
}
animate();

通过动态设置hue的值,改变圆的填充样式,就可以实现颜色渐变的粒子的粒子了,效果如开头第二幅动画。
在上面的基础上,还可以玩出新的花样,比如这样改动:

function animate() {
 // ctx.clearRect(0, 0, canvas.width, canvas.height);
 ctx.fillStyle = 'rgba(0, 0, 0, 0.2)';
 ctx.fillRect(0, 0, canvas.width, canvas.height);
 hue++;
 handleParticles();
 requestAnimationFrame(animate);
}

现在我们的粒子就有拖尾的效果了,就是文章开头的第三张动画,这里其实是通过整个画布透明度的叠加,让上一次的绘画效果变淡,最后隐藏起来了,从视觉效果上看就是渐变拖尾,到目前为止效果越来越有味了,但是代码还是很少喔。

5.连接的粒子

最后呢我们要实现粒子与粒子之间的连线,就是文章开头的第四幅动画效果,那么在前面的基础上,加上绘制两个圆之间的直线即可,当然这里要获取两个圆心的距离,然后进行绘制,这里涉及到handleParticles函数的改造,其他不变;

function handleParticles() {
 for (let i = 0; i < particlesArray.length; i++) {
  particlesArray[i].update();
  particlesArray[i].draw();
  // 从当前粒子开始,往后遍历后面的粒子,依次计算与之对应的距离
  for (let j = i + 1; j < particlesArray.length; j++) {
   const dx = particlesArray[i].x - particlesArray[j].x;
   const dy = particlesArray[i].y - particlesArray[j].y;
   const distance = Math.sqrt(dx * dx + dy * dy); // 初中知识
   if (distance < 100) { // 距离太大舍弃,否则视觉效果不好
    // 绘制直线
    ctx.beginPath();
    ctx.strokeStyle = `hsl(${hue}, 100%, 50%)`;
    ctx.moveTo(particlesArray[i].x, particlesArray[i].y);
    ctx.lineTo(particlesArray[j].x, particlesArray[j].y);
    ctx.stroke();
    ctx.closePath();
   }
  }
  if (particlesArray[i].size <= 0.3) {
   particlesArray.splice(i, 1);
   i--;
  }
 }
}

通过添加一个循环加直线绘制,效果就实现了,看起来还是很不错的,到这里基本是跟着作者走完一遍了,代码量不大,但是效果很不错,更重要的是对canvas的学习热情又起来了。

总结

到此这篇教你用几十行js实现很炫的canvas交互特效的文章就介绍到这了,更多相关js实现canvas交互特效内容请搜索华域联盟以前的文章或继续浏览下面的相关文章希望大家以后多多支持华域联盟!

本文由 华域联盟 原创撰写:华域联盟 » 教你用几十行js实现很炫的canvas交互特效

转载请保留出处和原文链接:https://www.cnhackhy.com/146596.htm

本文来自网络,不代表华域联盟立场,转载请注明出处。

作者: sterben

发表回复

联系我们

联系我们

2551209778

在线咨询: QQ交谈

邮箱: [email protected]

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们