JavaScript canvas realizes dynamic point and line effect

JavaScript canvas realizes dynamic point and line effect

This article shares the specific code for JavaScript canvas to achieve dynamic point and line effects for your reference. The specific content is as follows

Effect Preview

1. Achieve results

  • Draw colored dots
  • Connecting points
  • Point-line movement, encountering boundary rebound
  • Select a point and drag it to change its position*

2. Specific implementation

Initialize related variables

var c = document.getElementById("myCanvas");
      //Set canvas size c.height = document.body.offsetHeight;
      c.width = document.body.offsetWidth;
      //canvas follows the window size window.onresize = function() {
        c.height = document.body.offsetHeight;
        c.width = document.body.offsetWidth;
      };

      var theCanvas = c.getContext("2d");
      var pointList = []; //Store points
      var anim = null;
      var selectPoint = null;

Construct objects to store related point and line data

var PointLine = function(canvas, x, y, r, color) {
        this.theCanvas = canvas;
        this.x = x;
        this.y = y;
        this.r = r;
        this.color = color; //Point color this.speed = 5; //Point moving speed //Moving direction this.direction = parseInt(Math.random() * 1000) % 4; //0 -x 1 x 2-y 3 y
        this.drawPoint = function() {
          this.theCanvas.beginPath();
          this.theCanvas.fillStyle = this.color;
          this.theCanvas.arc(this.x, this.y, this.r, 0, 360);
          this.theCanvas.fill();
        };
        // Check if it is out of bounds, if so, change to the opposite direction this.checkX = function(x) {
          if (x - this.r <= 0) {
            this.x = this.r;
            this.direction = 1;
          } else if (x + this.r >= this.theCanvas.canvas.width) {
            this.x = this.theCanvas.canvas.width - this.r;
            this.direction = 0;
          } else this.x = x;
        };
        this.checkY = function(y) {
          if (y - this.r <= 0) {
            this.y = this.r;
            this.direction = 3;
          } else if (y + this.r >= this.theCanvas.canvas.height) {
            this.y = this.theCanvas.canvas.height - this.r;
            this.direction = 2;
          } else this.y = y;
        };
        //Move points this.movePoints = function() {
          if (this.direction == 0) {
            this.checkX(this.x - parseInt(Math.random() * this.speed));
          } else if (this.direction == 1) {
            this.checkX(this.x + parseInt(Math.random() * this.speed));
          } else if (this.direction == 2) {
            this.checkY(this.y - parseInt(Math.random() * this.speed));
          } else if (this.direction == 3) {
            this.checkY(this.y + parseInt(Math.random() * this.speed));
          }
        };
        return this;
      };

Draw a line between two points

//Connect two points function drawLine(start, end) {
        theCanvas.strokeStyle = "rgba(204,204,204,0.5)";
        theCanvas.beginPath();
        theCanvas.moveTo(start.x, start.y);
        theCanvas.lineTo(end.x, end.y);
        theCanvas.stroke();
      }
      //The distance between two points function getDistance(p1, p2) {
        return Math.pow(p1.x - p2.x, 2) + Math.pow(p1.y - p2.y, 2);
      }
      var minDistance = parseInt(0.1 * theCanvas.canvas.height);
      minDistance = minDistance * minDistance; //The shortest distance of a line //A point is connected to another point function drawLinkLine(p1) {
        for (var j = 0; j < pointList.length; j++) {
          var p2 = pointList[j];
          if (p2.x == p1.x && p2.y == p1.y) continue;

          var line = getDistance(p1, p2);
          if (line < minDistance && line > 0) {
            drawLine(p1, p2);
          }
        }
      }

Generate random points

//Generate random colors function randColor() {
        return (
          "rgb(" +
          [
            Math.floor(Math.random() * 255),
            Math.floor(Math.random() * 255),
            Math.floor(Math.random() * 255)
          ].join(",") +
          ")"
        );
      }
//Generate random points function createPoint() {
        var x = parseInt(Math.random() * theCanvas.canvas.width);
        var y = parseInt(Math.random() * theCanvas.canvas.height);
        var r = 5 + parseInt(Math.random() * 20);
        if (x - r < 0) x = r;
        else if (x + r > theCanvas.canvas.width) x = theCanvas.canvas.width - r;

        if (y - r < 0) x = r;
        else if (y + r > theCanvas.canvas.height)
          y = theCanvas.canvas.height - r;
        return new PointLine(theCanvas, x, y, r, randColor());
      }
      //Generate 100 random points for (var i = 0; i < 100; i++) {
        pointList.push(createPoint());
      }

Compatible with browser canvas animation frames

// Enable animation function canvasAnimation() {
        return (
          window.requestAnimationFrame ||
          window.webkitRequestAnimationFrame ||
          window.mozRequestAnimationFrame ||
          window.msRequestAnimationFrame ||
          function(callback, element) {
            var self = this,
              start,
              finish;
            window.setTimeout(function() {
              start = +new Date();
              callback(start);
              finish = +new Date();
              self.timeout = 1000 / 60 - (finish - start);
            }, self.timeout);
          }
        );
      }
      //Cancel animation function canvasCancleAnim() {
        return (
          window.cancelAnimationFrame ||
          window.webkitCancelAnimationFrame ||
          window.mozCancelAnimationFrame ||
          window.mosCancelAnimationFrame ||
          window.clearTimeout
        );
      }

Start Animation

//Loop execution of canvas animation function start() {
        anim = canvasAnimation()(this.start);
        // Clear the canvas
        theCanvas.clearRect(
          0,
          0,
          theCanvas.canvas.width,
          theCanvas.canvas.height
        );
        //Draw points and lines for (var i = 0; i < this.pointList.length; i++) {
          var p = pointList[i];
          drawLinkLine(p);
          p.drawPoint();
          if (selectPoint && selectPoint == p) continue;
          p.movePoints();
        }
      }

      //Start animation start();

Select a point and drag it

// px coordinates to canvas coordinates function windowToCanvas(canvas, x, y) {
        var bbox = canvas.getBoundingClientRect();
        return {
          x: x - bbox.left * (canvas.width / bbox.width),
          y: y - bbox.top * (canvas.height / bbox.height)
        };
      }
      //Set the action, press the selected point theCanvas.canvas.onmousedown = function(e) {
       
        var loc = windowToCanvas(theCanvas.canvas, e.clientX, e.clientY);      
        for (var i = 0; i < pointList.length; i++) {
          var p = pointList[i];
         
          if (getDistance(p, loc)<100) {
            selectPoint = p;
            break;
          }
        }
      };
      //Move point theCanvas.canvas.onmousemove = function(e) {
        if (selectPoint) {
          var loc = windowToCanvas(theCanvas.canvas, e.clientX, e.clientY);
          selectPoint.x = loc.x;
          selectPoint.y = loc.y;
         
        }
      };
      //Unselect the point theCanvas.canvas.onmouseup = function(e) {
        selectPoint = null;
       
      };

The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM.

You may also be interested in:
  • js+html5 method of drawing lines by specifying the start and end points of canvas

<<:  How to migrate mysql storage location to a new disk

>>:  MySQL triggers: creating and using triggers

Recommend

Apache Log4j2 reports a nuclear-level vulnerability and a quick fix

Apache Log4j2 reported a nuclear-level vulnerabil...

Detailed explanation of Docker data backup and recovery process

The data backup operation is very easy. Execute t...

Solution to Nginx SSL certificate configuration error

1. Introduction When a web project is published o...

The difference between KEY, PRIMARY KEY, UNIQUE KEY, and INDEX in MySQL

The problem raised in the title can be broken dow...

Analyze how a SQL query statement is executed in MySQL

Table of contents 1. Overview of MySQL Logical Ar...

The difference between HTML iframe and frameset_PowerNode Java Academy

Introduction 1.<iframe> tag: iframe is an i...

Key features of InnoDB - insert cache, write twice, adaptive hash index details

The key features of the InnoDB storage engine inc...

Manual and scheduled backup steps for MySQL database

Table of contents Manual backup Timer backup Manu...

Vue routing to implement login interception

Table of contents 1. Overview 2. Routing Navigati...

How to install mysql6 initialization installation password under centos7

1. Stop the database server first service mysqld ...

Detailed explanation of mysql partition function and example analysis

First, what is database partitioning? I wrote an ...

Why MySQL database avoids NULL as much as possible

Many tables in MySQL contain columns that can be ...

How to migrate local mysql to server database

We can use the scp command of Linux (scp cannot b...

Detailed explanation of the use of Join in Mysql

In the previous chapters, we have learned how to ...