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

How to quickly add columns in MySQL 8.0

Preface: I heard a long time ago that MySQL 8.0 s...

Introduction to Linux File Compression and Packaging

1. Introduction to compression and packaging Comm...

Common styles of CSS animation effects animation

animation Define an animation: /*Set a keyframe t...

Introduction to using data URI scheme to embed images in web pages

The data URI scheme allows us to include data in a...

CSS easily implements fixed-ratio block-level containers

When designing H5 layout, you will usually encoun...

Docker installs Elasticsearch7.6 cluster and sets password

Starting from Elasticsearch 6.8, free users are a...

Negative margin function introduction and usage summary

As early as in the CSS2 recommendations in 1998, t...

Summary of HTML knowledge points for the front end (recommended)

1. HTML Overview htyper text markup language Hype...

How to modify the port mapping of a running Docker container

Preface When docker run creates and runs a contai...

CSS implements six adaptive two-column layout methods

HTML structure <body> <div class="w...

Mysql date formatting and complex date range query

Table of contents Preface Query usage scenario ca...

Use of MySQL triggers

Triggers can cause other SQL code to run before o...

A comprehensive analysis of what Nginx can do

Preface This article only focuses on what Nginx c...