quhluh icon

Grabbing Mechanic For JavaScript

quhluh | 02/11/24 03:50:54 AM UTC | 0 ⭐ | 1219 👁️ | Never ⏰ | []
JavaScript |

2.1 KB

|

None

|

0 👍

/

0 👎

<!DOCTYPE html>
<html>
<head>
  <title>Grabbing Mechanic Example</title>
  <style>
    canvas {
      border: 1px solid black;
    }
  </style>
</head>
<body>
  <canvas id="canvas" width="400" height="400"></canvas>
 
  <script>
    // Get the canvas element
    const canvas = document.getElementById('canvas');
    const ctx = canvas.getContext('2d');
 
    // Create a circle object representing the object to be grabbed
    const circle = {
      x: canvas.width / 2,
      y: canvas.height / 2,
      radius: 20,
      color: 'blue',
      isGrabbed: false
    };
 
    // Add event listeners for mouse down, move, and up events
    canvas.addEventListener('mousedown', handleMouseDown);
    canvas.addEventListener('mousemove', handleMouseMove);
    canvas.addEventListener('mouseup', handleMouseUp);
 
    // Function to check if the mouse is within the circle
    function isInsideCircle(mouseX, mouseY) {
      const dx = mouseX - circle.x;
      const dy = mouseY - circle.y;
      return Math.sqrt(dx * dx + dy * dy) < circle.radius;
    }
 
    // Event handlers
    function handleMouseDown(event) {
      const mouseX = event.clientX - canvas.offsetLeft;
      const mouseY = event.clientY - canvas.offsetTop;
      if (isInsideCircle(mouseX, mouseY)) {
        circle.isGrabbed = true;
      }
    }
 
    function handleMouseMove(event) {
      const mouseX = event.clientX - canvas.offsetLeft;
      const mouseY = event.clientY - canvas.offsetTop;
      if (circle.isGrabbed) {
        circle.x = mouseX;
        circle.y = mouseY;
      }
    }
 
    function handleMouseUp() {
      circle.isGrabbed = false;
    }
 
    // Function to draw the circle
    function draw() {
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      ctx.beginPath();
      ctx.arc(circle.x, circle.y, circle.radius, 0, Math.PI * 2);
      ctx.fillStyle = circle.color;
      ctx.fill();
      ctx.closePath();
    }
 
    // Update and draw the scene
    function update() {
      draw();
      requestAnimationFrame(update);
    }
 
    update();
  </script>
</body>
</html>

Comments