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

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

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

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

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

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