【canvas】前端创造的图片粒子动画效果:HTML5 Canvas 技术详解

embedded/2024/9/24 12:37:32/

html" title=前端>前端创造的图片粒子动画效果:HTML5 Canvas 技术详解

我们将深入探讨如何通过 HTML5 的 Canvas 功能,将上传的图片转换成引人入胜的粒子动画效果。这种效果将图片分解成小粒子,并在用户与它们交互时产生动态变化。我们将分步骤详细解析代码,让你能够理解每一行代码的作用,并自己实现这一效果。
在这里插入图片描述

环境准备

首先,你需要一个简单的 HTML 元素和一些样式设置:

html"><!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Particle Image Animation from Uploaded Image</title><style>body {display: flex;justify-content: center;align-items: center;height: 100vh;margin: 0;background-color: #f0f0f0;overflow: hidden;}canvas, input {display: block;margin: auto;}</style>
</head>
<body><input type="file" id="upload" accept="image/*"><canvas id="canvas" hidden></canvas>
</body>
</html>

这段 HTML 设置了一个文件输入控件供用户上传图片,以及一个 Canvas 元素用于渲染动画效果。样式使页面内容居中显示,并将背景设置为浅灰色。

JavaScript 部分

JavaScript 脚本是这个效果的核心,下面我们逐一解析每个部分的功能。

1. 初始化和载入图片:
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
let particles = [];
const numOfParticles = 5000;
const uploadInput = document.getElementById('upload');uploadInput.addEventListener('change', function(event) {const file = event.target.files[0];if (file && file.type.startsWith('image')) {const reader = new FileReader();reader.onload = function(e) {const maxSize = 500; // 最大尺寸let width = img.width;let height = img.height;let scale = Math.min(maxSize / width, maxSize / height);if (scale < 1) {width *= scale;height *= scale;}canvas.width = width;canvas.height = height;ctx.drawImage(img, 0, 0, width, height);canvas.hidden = false;const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);createParticles(imageData);animate();};};reader.readAsDataURL(file);}
});

在这部分代码中,我们首先获取 Canvas 元素并配置基本画布(context)。监听文件输入控件的变化事件,当用户选择一个图片文件时,使用 FileReader 对象读取文件内容,将其转换为 Base64 编码的 URL,然后载入 <img> 元素。图片载入完毕后,把它绘制到 Canvas 上,然后提取图片的像素数据。

2. 创建粒子:
function createParticles(imageData) {particles = [];const { width, height } = imageData;for (let i = 0; i < numOfParticles; i++) {const x = Math.random() * width;const y = Math.random() * height;const color = imageData.data[(~~y * width + ~~x) * 4];particles.push(new Particle(x, y, color));}
}

这个函数根据图片的像素数据随机生成指定数量的粒子。每个粒子具有位置(x,y)和基于图片某一点的颜色。粒子的初始位置是随机分布的。

3. 定义粒子对象:
function Particle(x, y, color) {this.x = x;this.originalX = x;this.y = y;this.originalY = y;this.color = `rgba(${color},${color},${color}, 0.5)`;this.draw = function() {ctx.fillStyle = this.color;ctx.fillRect(this.x, this.y, 2, 2);};this.update = function() {let dx = this.originalX - this.x;let dy = this.originalY - this.y;this.x += dx * 0.1;this.y += dy * 0.1;this.draw();};
}

粒子对象具有 drawupdate 方法。draw 方法用来在 Canvas 上绘制粒子,update 方法则负责更新粒子的位置,使它们逐渐回到原始位置。

4. 动画循环和鼠标交互:
function animate() {ctx.clearRect(0, 0, canvas.width, canvas.height);particles.forEach(particle => particle.update());requestAnimationFrame(animate);
}

animate 函数清空画布并更新所有粒子的位置,然后通过 requestAnimationFrame 递归调用自身以形成动画循环。

完整代码

复制这段代码到一个.html文件,可以直接在浏览器允许该demo,实际操作一番。

html"><!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><title>Particle Image Animation from Uploaded Image</title><style>body {display: flex;justify-content: center;align-items: center;height: 100vh;margin: 0;background-color: #f0f0f0;overflow: hidden;}canvas,input {display: block;margin: auto;}</style>
</head><body><input type="file" id="upload" accept="image/*"><canvas id="canvas" hidden></canvas><script>const canvas = document.getElementById('canvas');const ctx = canvas.getContext('2d');let particles = [];const numOfParticles = 5000;const uploadInput = document.getElementById('upload');uploadInput.addEventListener('change', function (event) {const file = event.target.files[0];if (file && file.type.startsWith('image')) {const reader = new FileReader();reader.onload = function (e) {const img = new Image();img.src = e.target.result;img.onload = function () {const maxSize = 500; // 最大尺寸let width = img.width;let height = img.height;let scale = Math.min(maxSize / width, maxSize / height);if (scale < 1) {width *= scale;height *= scale;}canvas.width = width;canvas.height = height;ctx.drawImage(img, 0, 0, width, height);canvas.hidden = false;const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);createParticles(imageData);animate();};};reader.readAsDataURL(file);}});function createParticles(imageData) {particles = [];const { width, height } = imageData;for (let i = 0; i < numOfParticles; i++) {const x = Math.random() * width;const y = Math.random() * height;const color = imageData.data[(~~y * width + ~~x) * 4];particles.push(new Particle(x, y, color));}}function Particle(x, y, color) {this.x = x;this.originalX = x;this.y = y;this.originalY = y;this.color = `rgba(${color},${color},${color}, 0.5)`;this.draw = function () {ctx.fillStyle = this.color;ctx.fillRect(this.x, this.y, 2, 2);};this.update = function () {let dx = this.originalX - this.x;let dy = this.originalY - this.y;this.x += dx * 0.1;this.y += dy * 0.1;this.draw();};}function animate() {ctx.clearRect(0, 0, canvas.width, canvas.height);particles.forEach(particle => particle.update());requestAnimationFrame(animate);}canvas.addEventListener('mousemove', function (e) {const rect = canvas.getBoundingClientRect();const mouseX = e.clientX - rect.left;const mouseY = e.clientY - rect.top;particles.forEach(particle => {const dx = mouseX - particle.x;const dy = mouseY - particle.y;const dist = Math.sqrt(dx * dx + dy * dy);if (dist < 50) {const angle = Math.atan2(dy, dx);particle.x -= Math.cos(angle);particle.y -= Math.sin(angle);}});});</script>
</body></html>

http://www.ppmy.cn/embedded/16498.html

相关文章

08.OSPF的特殊区域及其特点

OSPF特殊区域 Stub 末梢区域&#xff0c;处在AS的边缘&#xff0c;只有连接其他区域的ABR&#xff0c;没有ASBR&#xff0c;没有虚连接穿越的非骨干区域 只能接收LSA1和LSA2与 LSA3&#xff0c;不能接收LSA4和LSA5区域内部路由与外部AS路由通信&#xff0c;由本区域的ABR&am…

如何看待AIGC技术

文章目录 前言如何看待AIGC技术AIGC可以应用到哪些领域 欢迎来到 请回答1024 的博客 &#x1f353;&#x1f353;&#x1f353;欢迎来到 请回答1024的博客 关于博主&#xff1a; 我是 请回答1024&#xff0c;一个追求数学与计算的边界、时间与空间的平衡&#xff0c;0与1的延伸…

Linux(Centos)服务器探索ffmpeg笔记 (命令行、Nvidia硬件加速、GPU、CPU、CUDA、h264_nvenc、过滤器、加水印)

目录 前言内容简介为什么会有这篇文章 1、服务器上怎么使用ffmpeg1.1 使用编译好的&#xff08;需要root权限&#xff09;1.2 自己怎么编译&#xff08;需要root权限&#xff09; 2 、非Root用户要怎么安装和使用3、ffmpeg命令的一些使用引导和参数介绍3.1 编译参数3.2 查询支持…

使用git将本地项目上传到github

大致的流程是&#xff1a;创建本地仓库&#xff0c;把代码传到本地仓库&#xff0c;把本地仓库内容传到远程仓库。还不太完整&#xff0c;逐渐摸索使用吧 1、初始化仓库 git init在本地项目的路径中初始化一个仓库。 2、提交到本地 选择需要上传的文件 git add .提交到本地…

Github学生认证

Github学生认证 文章目录 前言一、前期准备1.1. 添加学校邮箱1.2. 开通2FA双重身份验证1.3. 在线验证报告1.4. 完善基础信息 二、Github学生认证总结 前言 为了免费使用GitHub Copilot&#xff0c;故在github中申请学生认证。 一、前期准备 1.1. 添加学校邮箱 申请完学校邮箱…

提示工程 1—常用的大语言模型参数说明

1. 常用的大语言模型参数说明 使用提示词时,会通过 API 或直接与大语言模型进行交互。我们可以通过配置一些参数以获得不同的提示结果。调整这些设置对于提高响应的可靠性非常重要,我们可能需要进行一些实验才能找出适合您的用例的正确设置。以下是一些常见的参数设置: 1.…

专项技能训练五《云计算网络技术与应用》实训6-1:安装OpenDayLight控制器

文章目录 OpenDayLight环境安装及常用操作1. 使用VMware安装CentOS 7虚拟机&#xff0c;安装时需添加多一张网卡&#xff0c;该网卡为自定义-VMnet1.并且记得开启CPU虚拟化&#xff0c;将其命名为“OpenDayLight”。2. 安装完虚拟机后&#xff0c;进入虚拟机&#xff0c;修改网…

【年报文本分析】第二辑:python+selium实现根据股票代码和对应年份获取上市公司年报链接(巨潮资讯网)

目录 序言excel文件准备函数模块介绍创建模拟浏览器对象只需要执行一次的部分需要批量执行的重复操作部分&#xff08;信息录入excel&#xff09;主函数 本地文件结构全部代码结果预览 本文以指定的A股公司年报为例&#xff0c;从巨潮资讯网上获取。 该方法建议需要特定年报数据…