This article will introduce to you how to use HTML5 canvas to draw cool energy line effects. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

The above is the rendering, and the js code is directly attached below. I hope it will be helpful to everyone! !
// UTILconst PI = Math.PI,
TWO_PI = Math.PI * 2;const Util = {};Util.timeStamp = function() {
return window.performance.now();};Util.random = function(min, max) {
return min + Math.random() * (max - min);};Util.map = function(a, b, c, d, e) {
return (a - b) / (c - b) * (e - d) + d;};Util.lerp = function(value1, value2, amount) {
return value1 + (value2 - value1) * amount;};Util.clamp = function(value, min, max) {
return Math.max(min, Math.min(max, value));};// Vectorclass Vector {
constructor(x, y) {
this.x = x || 0;
this.y = y || 0;
}
set(x, y) {
this.x = x;
this.y = y;
}
reset() {
this.x = 0;
this.y = 0;
}
fromAngle(angle) {
let x = Math.cos(angle),
y = Math.sin(angle);
return new Vector(x, y);
}
add(vector) {
this.x += vector.x;
this.y += vector.y;
}
sub(vector) {
this.x -= vector.x;
this.y -= vector.y;
}
mult(scalar) {
this.x *= scalar;
this.y *= scalar;
}
p(scalar) {
this.x /= scalar;
this.y /= scalar;
}
dot(vector) {
return vector.x * this.x + vector.y * this.y;
}
limit(limit_value) {
if (this.mag() > limit_value) this.setMag(limit_value);
}
mag() {
return Math.hypot(this.x, this.y);
}
setMag(new_mag) {
if (this.mag() > 0) {
this.normalize();
} else {
this.x = 1;
this.y = 0;
}
this.mult(new_mag);
}
normalize() {
let mag = this.mag();
if (mag > 0) {
this.x /= mag;
this.y /= mag;
}
}
heading() {
return Math.atan2(this.y, this.x);
}
setHeading(angle) {
let mag = this.mag();
this.x = Math.cos(angle) * mag;
this.y = Math.sin(angle) * mag;
}
dist(vector) {
return new Vector(this.x - vector.x, this.y - vector.y).mag();
}
angle(vector) {
return Math.atan2(vector.y - this.y, vector.x - this.x);
}
copy() {
return new Vector(this.x, this.y);
}}// Init canvaslet canvas = document.createElement("canvas"),
ctx = canvas.getContext("2d"),
H = (canvas.height = window.innerHeight),
W = (canvas.width = window.innerWidth);document.body.appendChild(canvas);// Mouselet mouse = {
x: W/2,
y: H/2};canvas.onmousemove = function(event) {
mouse.x = event.clientX - canvas.offsetLeft;
mouse.y = event.clientY - canvas.offsetTop;};document.body.onresize = function(event){
H = (canvas.height = window.innerHeight);
W = (canvas.width = window.innerWidth);}// Let's goclass Arrow {
constructor(x, y, target) {
this.position = new Vector(x, y);
this.velocity = new Vector().fromAngle(Util.random(0,TWO_PI));
this.acceleration = new Vector(0, 0);
this.target = target;
this.travelled_distance = 0;
this.min_size = 1;
this.max_size = 6;
this.size = Util.random(this.min_size, this.max_size);
this.zone = this.size * 4;
this.topSpeed = Util.map(this.size,this.min_size,this.max_size,40,10);
let tailLength = Math.floor(Util.map(this.size, this.min_size, this.max_size, 4, 16));
this.tail = [];
for (let i = 0; i < tailLength; i++) {
this.tail.push({
x: this.position.x,
y: this.position.y });
}
this.wiggle_speed = Util.map(this.size, this.min_size, this.max_size, 2 , 1.2);
this.blink_offset = Util.random(0, 100);
this.alpha = Util.random(0.1,1)
}
render() {
this.update();
this.draw();
}
update() {
let old_position = this.position.copy();
// Focus on target
let t = new Vector(this.target.x, this.target.y),
angle = this.position.angle(t);
let d_f_target = t.dist(this.position);
let f = new Vector().fromAngle(angle);
f.setMag(Util.map(Util.clamp(d_f_target,0,400), 0, 400, 0, this.topSpeed * 0.1));
this.addForce(f);
// Update position and velocity
this.velocity.add(this.acceleration);
if(d_f_target < 800){
this.velocity.limit(Util.map(Util.clamp(d_f_target,0,800), 0, 800, this.topSpeed*0.4, this.topSpeed));
}else{
this.velocity.limit(this.topSpeed);
}
this.position.add(this.velocity);
// Reset acceleration for the next loop
this.acceleration.mult(0);
this.travelled_distance += old_position.dist(this.position);
let wiggle =
Math.sin(frame * this.wiggle_speed) *
Util.map(this.velocity.mag(), 0, this.topSpeed, 0, this.size);
let w_a = this.velocity.heading() + Math.PI / 2;
let w_x = this.position.x + Math.cos(w_a) * wiggle,
w_y = this.position.y + Math.sin(w_a) * wiggle;
this.travelled_distance = 0;
let from = this.tail.length - 1,
to = 0;
let n = new Vector().fromAngle(Util.random(0,TWO_PI));
n.setMag(Math.random()*this.size);
var tail = { x: w_x+ n.x, y: w_y + n.y};
this.tail.splice(from, 1);
this.tail.splice(to, 0, tail);
}
draw() {
let energy = Util.map(this.velocity.mag(),0,this.topSpeed,0.1,1);
let color =
"hsl("+Math.sin((frame + this.blink_offset) * 0.1) * 360+",50%,"+
Util.map(this.velocity.mag(),0,this.topSpeed,40,100) * this.alpha
+"%)";
ctx.globalAlpha = this.alpha;
ctx.strokeStyle = color;
for (let i = 0; i < this.tail.length - 1; i++) {
let t = this.tail[i],
next_t = this.tail[i + 1];
ctx.lineWidth = Util.map(i, 0, this.tail.length - 1, this.size, 1);
ctx.beginPath();
ctx.moveTo(t.x, t.y);
ctx.lineTo(next_t.x, next_t.y);
ctx.closePath();
ctx.stroke();
}
let gradient_size = 140 * energy;var grd = ctx.createRadialGradient(
this.position.x,this.position.y , 5,
this.position.x,this.position.y, gradient_size);grd.addColorStop(0, "rgba(255,255,255,0.01)");grd.addColorStop(0.1, "rgba(255,120,200,0.02)");grd.addColorStop(0.9, "rgba(255,255,120,0)");grd.addColorStop(1, "rgba(0,0,0,0)");// Fill with gradientctx.fillStyle = grd;ctx.fillRect(this.position.x - gradient_size / 2 ,this.position.y - gradient_size / 2 , gradient_size, gradient_size);
ctx.globalAlpha = energy+0.2;
ctx.fillStyle = "white";
for(let i = 0; i < 4; i++){
let n = new Vector().fromAngle(Util.random(0,TWO_PI));
n.setMag(Math.random()*energy*100);
n.add(this.position);
ctx.beginPath();
ctx.arc(n.x,n.y,Math.random(),0,TWO_PI)
ctx.fill();
}
}
addForce(vector) {
this.acceleration.add(vector);
}
avoid(others) {
others.forEach(other => {
if (other !== this) {
let dist = this.position.dist(other.position),
max_dist = this.zone + other.size;
if (max_dist - dist >= 0) {
let angle = other.position.angle(this.position);
let force = new Vector().fromAngle(angle);
force.setMag(Util.map(dist, 0, max_dist, 2, 0));
this.addForce(force);
}
}
});
}}let arrows = [];for (let i = 0; i < 100; i++) {
arrows.push(new Arrow(W / 2, H / 2, mouse));}let frame = 0;ctx.strokeStyle = "white";function loop() {
ctx.fillStyle="black";
ctx.globalCompositeOperation = "source-over";
ctx.globalAlpha = 0.2;
ctx.fillRect(0, 0, W, H);
ctx.globalAlpha = 1;
ctx.globalCompositeOperation = "lighter";
arrows.forEach(a => {
a.avoid(arrows);
});
arrows.forEach(a => {
a.render();
});
frame += 1;
requestAnimationFrame(loop);}ctx.lineCap = "round";ctx.lineJoin = "round";loop();Recommended learning: Html5 video tutorial
The above is the detailed content of How to draw cool energy line effects on HTML5 canvas (with code). For more information, please follow other related articles on the PHP Chinese website!
H5 Code: Best Practices for Web DevelopersApr 16, 2025 am 12:14 AMBest practices for H5 code include: 1. Use correct DOCTYPE declarations and character encoding; 2. Use semantic tags; 3. Reduce HTTP requests; 4. Use asynchronous loading; 5. Optimize images. These practices can improve the efficiency, maintainability and user experience of web pages.
H5: The Evolution of Web Standards and TechnologiesApr 15, 2025 am 12:12 AMWeb standards and technologies have evolved from HTML4, CSS2 and simple JavaScript to date and have undergone significant developments. 1) HTML5 introduces APIs such as Canvas and WebStorage, which enhances the complexity and interactivity of web applications. 2) CSS3 adds animation and transition functions to make the page more effective. 3) JavaScript improves development efficiency and code readability through modern syntax of Node.js and ES6, such as arrow functions and classes. These changes have promoted the development of performance optimization and best practices of web applications.
Is H5 a Shorthand for HTML5? Exploring the DetailsApr 14, 2025 am 12:05 AMH5 is not just the abbreviation of HTML5, it represents a wider modern web development technology ecosystem: 1. H5 includes HTML5, CSS3, JavaScript and related APIs and technologies; 2. It provides a richer, interactive and smooth user experience, and can run seamlessly on multiple devices; 3. Using the H5 technology stack, you can create responsive web pages and complex interactive functions.
H5 and HTML5: Commonly Used Terms in Web DevelopmentApr 13, 2025 am 12:01 AMH5 and HTML5 refer to the same thing, namely HTML5. HTML5 is the fifth version of HTML, bringing new features such as semantic tags, multimedia support, canvas and graphics, offline storage and local storage, improving the expressiveness and interactivity of web pages.
What Does H5 Refer To? Exploring the ContextApr 12, 2025 am 12:03 AMH5referstoHTML5,apivotaltechnologyinwebdevelopment.1)HTML5introducesnewelementsandAPIsforrich,dynamicwebapplications.2)Itsupportsmultimediawithoutplugins,enhancinguserexperienceacrossdevices.3)SemanticelementsimprovecontentstructureandSEO.4)H5'srespo
H5: Tools, Frameworks, and Best PracticesApr 11, 2025 am 12:11 AMThe tools and frameworks that need to be mastered in H5 development include Vue.js, React and Webpack. 1.Vue.js is suitable for building user interfaces and supports component development. 2.React optimizes page rendering through virtual DOM, suitable for complex applications. 3.Webpack is used for module packaging and optimize resource loading.
The Legacy of HTML5: Understanding H5 in the PresentApr 10, 2025 am 09:28 AMHTML5hassignificantlytransformedwebdevelopmentbyintroducingsemanticelements,enhancingmultimediasupport,andimprovingperformance.1)ItmadewebsitesmoreaccessibleandSEO-friendlywithsemanticelementslike,,and.2)HTML5introducednativeandtags,eliminatingthenee
H5 Code: Accessibility and Semantic HTMLApr 09, 2025 am 12:05 AMH5 improves web page accessibility and SEO effects through semantic elements and ARIA attributes. 1. Use, etc. to organize the content structure and improve SEO. 2. ARIA attributes such as aria-label enhance accessibility, and assistive technology users can use web pages smoothly.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft






