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

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

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

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

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

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