Effect: particles will move and a line will appear between particles within a certain range.





rendering

demo

Here’s how to do it

Get canvas object and brush
var canvas = document.getElementById("canvas")
var ctx = canvas.getContext("2d")
// Save the canvas width and height
var w = canvas.offsetWidth
var h = canvas.offsetHeight
// Note: Canvas actually has two sets of sizes, one is its own size, and the other is the size of the drawing surface
canvas.width = w
canvas.height = hCopy the code
Create point classes

In effect there are many points, and each point has the same properties like coordinates, radius, velocity, etc

function Point(x, y) {
    this.x = x 
    this.y = y
    this.r = 1 + Math.random() * 2
    this.sx = Math.random() * 2 - 1
    this.sy = Math.random() * 2 - 1
}Copy the code
3. Add the method of drawing points to Point

First of all, there is nothing on the canvas, so there is a point before you can continue the action

Point.prototype.draw = function(ctx) {
    ctx.beginPath()
    ctx.arc(this.x, this.y, this.r, 0.2 * Math.PI)
    ctx.closePath()
    ctx.fillStyle = '#aaa'
    ctx.fill()
}Copy the code
Add Point action to Point
Point.prototype.move = function() {
    this.x += this.sx
    this.y += this.sy
    if(this.x > w || this.x < 0) this.sx = -this.sx
    if(this.y > h || this.y < 0) this.sy = -this.sy
}Copy the code
Five, the connection between points — draw lines
Point.prototype.drawLine = function(ctx, p) {
    var dx = this.x - p.x 
    var dy = this.y - p.y
    var d = Math.sqrt(dx * dx + dy * dy)
    if(d < 100) {
        var alpha = (100 - d) / 100 * 1 
        ctx.beginPath()
        ctx.moveTo(this.x, this.y)
        ctx.lineTo(p.x, p.y)
        ctx.closePath()
        ctx.strokeStyle = 'rgba(170, 170, 170, ' + alpha + ') '
        ctx.strokeWidth = 1
        ctx.stroke()
    }
}Copy the code
6. Instantiation point

Now I’m going to take those points and store each point in an array.

var points = []

for(var i = 0; i < 40; i++) {
    points.push(new Point(Math.random() * w, Math.random() * h))
}Copy the code
Seven, draw point

Take the points array one by one and call the points methods: Draw, move, line, and paint().

function paint() {
    ctx.clearRect(0.0, w, h) // Empty the canvas
    for(var i = 0; i < points.length; i++) {
        points[i].move(a)points[i].draw(ctx)
        for(var j = i + 1; j < points.length; j++) {
            points[i].drawLine(ctx, points[j])
        }
    }
}
// Use requestAnimationFrame to update the screen
function loop() {
    requestAnimationFrame(loop)
    paint()}loop(a)Copy the code