Advertisement
lemansky

Untitled

Dec 11th, 2020
518
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
HTML 2.43 KB | None | 0 0
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4.     <meta charset="UTF-8">
  5.     <title>Document</title>
  6.     <script type="text/javascript">
  7.     document.addEventListener("DOMContentLoaded", function(){
  8.         let canvas = document.getElementById('canvasId');
  9.         let canvasId = canvas.getContext("2d");  
  10.         let mouse;
  11.         let cubes = [];
  12.         let activeColor = 'red';
  13.  
  14.        
  15.         for (let i = 1; i <= 10; i++) {
  16.            let newCube = new ColorCube(canvas.width - 50*i - 10*i);
  17.            canvasId.beginPath();
  18.            canvasId.fillStyle = newCube.color;
  19.            canvasId.rect(newCube.x, newCube.y, newCube.w, newCube.h);
  20.            canvasId.fill();
  21.            canvasId.closePath();
  22.            cubes.push(newCube);
  23.        }
  24.        console.log(cubes);
  25.  
  26.        const handler = (mouse) => {
  27.             canvasId.lineTo(mouse.x, mouse.y);
  28.             canvasId.stroke();
  29.             // canvasId.closePath();
  30.         }
  31.  
  32.         canvas.addEventListener('click', function(evt){
  33.            
  34.             mouse = mouse_player1(evt, canvas);
  35.             canvasId.beginPath();
  36.             canvasId.strokeStyle = activeColor;
  37.             canvasId.moveTo(mouse.x, mouse.y);
  38.             canvas.addEventListener('mousemove', handler);
  39.  
  40.         });
  41.        
  42.     });
  43.  
  44.     const mouse_player1 = (evt, canvas) => {
  45.         var rect = canvas.getBoundingClientRect(); // взима позицията на платното в документа, в случай, че то не започва от горния ляв ъгъл
  46.         var mouseX = evt.clientX - rect.left; // позицията на курсора по хоризонтала
  47.         var mouseY = evt.clientY - rect.top; // позиията на курсора по вертикала
  48.         return {
  49.             x: mouseX,
  50.             y: mouseY,
  51.         } // фунцкията връша два параметъра, x и y
  52.     }
  53.  
  54.     class ColorCube{
  55.         constructor(x){
  56.             this.x = x;
  57.             this.y = 750;
  58.             this.w = 50;
  59.             this.h = 50;
  60.             this.color = "rgb(" + Math.floor(Math.random()*255 + 1) + ", " + Math.floor(Math.random()*255 + 1) + ", " + Math.floor(Math.random()*255 + 1) + ")";
  61.         }
  62.     }
  63.    
  64. </script>
  65. <style>
  66.     canvas{
  67.         background-color: black;
  68.     }
  69. </style>
  70. </head>
  71. <body style="margin:0px;">
  72.   <canvas width="800" height="800" id="canvasId"></canvas>
  73. </body>
  74. </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement