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

About IE8 compatibility: Explanation of the X-UA-Compatible attribute

Problem description: Copy code The code is as fol...

Analysis of MySQL example DTID master-slave principle

Table of contents 1. Basic Concepts of GTID 2. GT...

Discussion on default margin and padding values ​​of common elements

Today we discussed the issue of what the margin v...

Embed player in web page embed element autostart false invalid

Recently, I encountered the need to embed a player...

Pure HTML and CSS to achieve JD carousel effect

The JD carousel was implemented using pure HTML a...

Common methods of Vue componentization: component value transfer and communication

Related knowledge points Passing values ​​from pa...

Docker builds kubectl image implementation steps

If the program service is deployed using k8s inte...

Native JS to achieve book flipping effects

This article shares with you a book flipping effe...

In-depth explanation of closure in JavaScript

Introduction Closure is a very powerful feature i...

Zabbix monitors Linux hosts based on snmp

Preface: The Linux host is relatively easy to han...

Detailed explanation of Javascript event capture and bubbling methods

Table of contents 1. Event Processing Model 1. Ev...

React Native environment installation process

react-native installation process 1.npx react-nat...

How to uninstall MySQL cleanly (tested and effective)

How to uninstall Mysql perfectly? Follow the step...