• 几十行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的学习热情又起来了。

    福禄·研发中心 福袋
  • 相关阅读:
    (5)基于协同过滤推荐算法的图书推荐研究
    (4)推荐系统评测方法和指标分析
    (3)浅析机器学习在推荐系统中的应用
    (2)协同过滤推荐算法概述 摘要
    (1)推荐系统概述 -- 摘要
    30+简约时尚的Macbook贴花
    20+非常棒的Photoshop卡通设计教程
    20+WordPress手机主题和插件【好收藏推荐】
    30+WordPress古典风格的主题-古典却不失时尚
    配置FCKeditor_2.6.3+fckeditor-java-2.4
  • 原文地址:https://www.cnblogs.com/fulu/p/15511585.html
Copyright © 2020-2023  润新知