Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>Document</title>
- <script type="text/javascript">
- document.addEventListener("DOMContentLoaded", function(){
- let canvas = document.getElementById('canvasId');
- let context = canvas.getContext("2d");
- class Shape{
- constructor(x, y, w, h, color){
- this.x = x;
- this.y = y;
- this.w = w;
- this.h = h;
- this.color = color;
- this.ogColor = color;
- }
- }
- let shapes = [];
- for (let index = 0; index < 10; index++) {
- let myRectangle = new Shape(
- Math.floor(Math.random()*701),
- Math.floor(Math.random()*701),
- Math.floor(Math.random()*(100 - 50 + 1) + 50),
- Math.floor(Math.random()*(100 - 50 + 1) + 50),
- // Math.floor(Math.random()*(max - min + 1) + min)
- 'rgb('+ Math.floor(Math.random()*256) + ', ' +
- Math.floor(Math.random()*256) + ', ' +
- Math.floor(Math.random()*256) + ')'
- );
- shapes.push(myRectangle);
- context.fillStyle = myRectangle.color;
- context.fillRect(myRectangle.x, myRectangle.y, myRectangle.w, myRectangle.h);
- }
- canvas.addEventListener('click', (e) => {
- let mouse = mouse_player1(e, canvas);
- let isOnPath = false;
- for (iterator of shapes) {
- let myPath = new Path2D();
- context.beginPath();
- myPath.rect(iterator.x, iterator.y, iterator.w, iterator.h);
- context.closePath();
- if(context.isPointInPath(myPath, mouse.x, mouse.y)){
- isOnPath = true;
- for (let index = 0; index < shapes.length; index++) {
- if(iterator.color != iterator.ogColor){
- shapes[index].color = iterator.ogColor;
- } else {
- shapes[index].color = iterator.color;
- }
- }
- }
- }
- context.clearRect(0, 0, canvas.width, canvas.height);
- if(!isOnPath){
- for(item of shapes){
- item.x = Math.floor(Math.random()*701);
- item.y = Math.floor(Math.random()*701);
- item.color = item.ogColor;
- }
- }
- for(item of shapes){
- context.fillStyle = item.color;
- context.fillRect(item.x, item.y, item.w, item.h);
- }
- });
- });
- const mouse_player1 = (evt, canvas) => {
- var rect = canvas.getBoundingClientRect(); // взима позицията на платното в документа, в случай, че то не започва от горния ляв ъгъл
- var mouseX = evt.clientX - rect.left; // позицията на курсора по хоризонтала
- var mouseY = evt.clientY - rect.top; // позиията на курсора по вертикала
- return {
- x: mouseX,
- y: mouseY,
- } // фунцкията връша два параметъра, x и y
- }
- </script>
- <style>
- canvas{
- background-color: black;
- }
- </style>
- </head>
- <body>
- <canvas width="800" height="800" id="canvasId"></canvas>
- </body>
- </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement