Advertisement
lemansky

Untitled

Dec 4th, 2023
663
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
HTML 2.22 KB | None | 0 0
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4.   <meta charset="UTF-8">
  5.   <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6.   <title>Canvas Rotation</title>
  7.   <style>
  8.     canvas{
  9.       background: black;
  10.     }
  11.   </style>
  12. </head>
  13. <body>
  14.   <canvas width="600" height="400" ></canvas>
  15.  
  16.   <script>
  17.  
  18.     const canvas = document.querySelector('canvas');
  19.     const ctx = canvas.getContext("2d");
  20.  
  21.  
  22.     let rotateRectangle = (x, y, width, height, angle) => {
  23.       let radians = angle * (Math.PI / 180);
  24.       let centerX = x + width / 2;
  25.       let centerY = y + height / 2;
  26.  
  27.       let newX1 = Math.cos(radians) * (x - centerX) - Math.sin(radians) * (y - centerY) + centerX;
  28.       let newY1 = Math.sin(radians) * (x - centerX) + Math.cos(radians) * (y - centerY) + centerY;
  29.  
  30.       let newX2 = Math.cos(radians) * (x + width - centerX) - Math.sin(radians) * (y - centerY) + centerX;
  31.       let newY2 = Math.sin(radians) * (x + width - centerX) + Math.cos(radians) * (y - centerY) + centerY;
  32.  
  33.       let newX3 = Math.cos(radians) * (x + width - centerX) - Math.sin(radians) * (y + height - centerY) + centerX;
  34.       let newY3 = Math.sin(radians) * (x + width - centerX) + Math.cos(radians) * (y + height - centerY) + centerY;
  35.  
  36.       let newX4 = Math.cos(radians) * (x - centerX) - Math.sin(radians) * (y + height - centerY) + centerX;
  37.       let newY4 = Math.sin(radians) * (x - centerX) + Math.cos(radians) * (y + height - centerY) + centerY;
  38.  
  39.       return { newX1, newY1, newX2, newY2, newX3, newY3, newX4, newY4 };
  40.     }
  41.  
  42.     ctx.fillStyle = "blue";
  43.     ctx.fillRect(100, 100, 100, 20);
  44.  
  45.     let originalX = 100;
  46.     let originalY = 100;
  47.     let originalWidth = 100;
  48.     let originalHeight = 20;
  49.     let rotationAngle = 30;
  50.  
  51.     let rotatedPositions = rotateRectangle(originalX, originalY, originalWidth, originalHeight, rotationAngle);
  52.  
  53.     ctx.fillStyle = "red";
  54.     ctx.beginPath();
  55.     ctx.moveTo(rotatedPositions.newX1, rotatedPositions.newY1);
  56.     ctx.lineTo(rotatedPositions.newX2, rotatedPositions.newY2);
  57.     ctx.lineTo(rotatedPositions.newX3, rotatedPositions.newY3);
  58.     ctx.lineTo(rotatedPositions.newX4, rotatedPositions.newY4);
  59.     ctx.closePath();
  60.     ctx.fill();
  61.  
  62.  
  63.   </script>
  64. </body>
  65. </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement