quhluh

Grabbing Mechanic For JavaScript

Feb 10th, 2024
1,251
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4.   <title>Grabbing Mechanic Example</title>
  5.   <style>
  6.     canvas {
  7.       border: 1px solid black;
  8.     }
  9.   </style>
  10. </head>
  11. <body>
  12.   <canvas id="canvas" width="400" height="400"></canvas>
  13.  
  14.   <script>
  15.     // Get the canvas element
  16.     const canvas = document.getElementById('canvas');
  17.     const ctx = canvas.getContext('2d');
  18.  
  19.     // Create a circle object representing the object to be grabbed
  20.     const circle = {
  21.       x: canvas.width / 2,
  22.       y: canvas.height / 2,
  23.       radius: 20,
  24.       color: 'blue',
  25.       isGrabbed: false
  26.     };
  27.  
  28.     // Add event listeners for mouse down, move, and up events
  29.     canvas.addEventListener('mousedown', handleMouseDown);
  30.     canvas.addEventListener('mousemove', handleMouseMove);
  31.     canvas.addEventListener('mouseup', handleMouseUp);
  32.  
  33.     // Function to check if the mouse is within the circle
  34.     function isInsideCircle(mouseX, mouseY) {
  35.       const dx = mouseX - circle.x;
  36.       const dy = mouseY - circle.y;
  37.       return Math.sqrt(dx * dx + dy * dy) < circle.radius;
  38.     }
  39.  
  40.     // Event handlers
  41.     function handleMouseDown(event) {
  42.       const mouseX = event.clientX - canvas.offsetLeft;
  43.       const mouseY = event.clientY - canvas.offsetTop;
  44.       if (isInsideCircle(mouseX, mouseY)) {
  45.         circle.isGrabbed = true;
  46.       }
  47.     }
  48.  
  49.     function handleMouseMove(event) {
  50.       const mouseX = event.clientX - canvas.offsetLeft;
  51.       const mouseY = event.clientY - canvas.offsetTop;
  52.       if (circle.isGrabbed) {
  53.         circle.x = mouseX;
  54.         circle.y = mouseY;
  55.       }
  56.     }
  57.  
  58.     function handleMouseUp() {
  59.       circle.isGrabbed = false;
  60.     }
  61.  
  62.     // Function to draw the circle
  63.     function draw() {
  64.       ctx.clearRect(0, 0, canvas.width, canvas.height);
  65.       ctx.beginPath();
  66.       ctx.arc(circle.x, circle.y, circle.radius, 0, Math.PI * 2);
  67.       ctx.fillStyle = circle.color;
  68.       ctx.fill();
  69.       ctx.closePath();
  70.     }
  71.  
  72.     // Update and draw the scene
  73.     function update() {
  74.       draw();
  75.       requestAnimationFrame(update);
  76.     }
  77.  
  78.     update();
  79.   </script>
  80. </body>
  81. </html>
Advertisement
Add Comment
Please, Sign In to add comment