How to Pick or Select and Move polygon object on mouse click in html5 canvas

how to identify polygon object in html5 canvas using javascript - Nibunan

how to draw the polygon object in html5 canvas using javascript - Nibunan

how to find the polygon object in html5 canvas using javascript - Nibunan

how to pick the polygon object in html5 canvas using javascript - Nibunan

Html5 canvas is evolving to give the rich graphics on browser without using flash or other plugins. Html5 canvas is being used in many places like games animations and rich user interfaces on web and so on.This article explains how to create the polygon in html5 canvas using javascript and identify or picking the polygon object when clicking the mouse on that object. And also explains how to move it when mouse move.

Demo

Open with new tab

Source


      <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
      <html xmlns="http://www.w3.org/1999/xhtml">
      <head>
      <title>Pick or select and move polygon on mouse click in html5 canvas - Nibunan</title>
      </head>
      <body style="margin: 0px">
      <script src="http://nibunan.com/build/extend-canvas.min.js"></script>
      <script type="text/javascript">
      function Random(range) {
      return Math.floor((Math.random() * range) + 1);
      }
      var selectedPolygon = null;
      var previousMouseX = 0;
      var previousMouseY = 0;
      var geoport = new Geoport();
      var context = geoport.Create2dContext();
      var polygonMouseDown = function (e) {
      previousMouseX = e.x;
      previousMouseY = e.y;
      selectedPolygon = e.sender;
      }
      for (var i = 0; i < 10; i++) {
      var x = Random(window.innerWidth-200)+100;
      var y = Random(window.innerHeight - 200) + 100;
      var points = [
      new Point(x, y),
      new Point(x + 100, y - 100),
      new Point(x + 200, y),
      new Point(x + 150, y+100),
      new Point(x + 50, y+100)];
      var polygon = new Polygon(points);
      polygon.BorderWidth = 2;
      polygon.Color = new Color(Random(254) + 1, Random(254) + 1, Random(254) + 1);
      polygon.FillColor = new Color(Random(254) + 1, Random(254) + 1, Random(254) + 1);
      polygon.AlphaStroke = Random(254) + 50;
      polygon.AlphaFill = Random(254) + 50;
      polygon.AddMouseDownEvent(polygonMouseDown);
      context.Add(polygon);
      }

      geoport.AddMouseMoveEvent(function (e) {
      var diffx = previousMouseX - e.x;
      var diffy = previousMouseY - e.y;
      previousMouseX = e.x;
      previousMouseY = e.y;
      var loc = new Point();
      loc.x = selectedPolygon.Origin.x - diffx;
      loc.y = selectedPolygon.Origin.y - diffy;
      if (selectedPolygon != null) {
      selectedPolygon.Move(loc);
      }
      });
      geoport.AddMouseUpEvent(function (e) {
      selectedPolygon = null;
      });
      geoport.Initiate();
      </script>
      </body>
      </html>