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

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

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

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

how to pick the rectangle 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 rectangle in html5 canvas using javascript and identify or picking the rectangle 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 rectangle 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 selectedRect = null;
      var previousMouseX = 0;
      var previousMouseY = 0;
      var geoport = new Geoport();
      var context = geoport.Create2dContext();
      var rectangleMouseDown = function (e) {
      previousMouseX = e.x;
      previousMouseY = e.y;
      selectedRect = e.sender;
      }
      for (var i = 0; i < 10; i++) {
      var rect = new Rectangle2D(new Point(Random(window.innerWidth - 200) + 10, Random(window.innerHeight - 200) + 10), new Size(Random(50) + 100, Random(50) + 100));
      rect.BorderWidth = 2;
      rect.Color = new Color(Random(254) + 1, Random(254) + 1, Random(254) + 1);
      rect.FillColor = new Color(Random(254) + 1, Random(254) + 1, Random(254) + 1);
      rect.AlphaStroke = Random(254) + 50;
      rect.AlphaFill = Random(254) + 50;
      rect.AddMouseDownEvent(rectangleMouseDown);
      context.Add(rect);
      }

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