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 canvasId = canvas.getContext("2d");
- let mouse;
- let cubes = [];
- let activeColor = 'red';
- let isActive = false;
- canvasId.lineWidth = 10;
- for (let i = 1; i <= 10; i++) {
- let newCube = new ColorCube(canvas.width - 50*i - 10*i);
- canvasId.beginPath();
- canvasId.fillStyle = newCube.color;
- canvasId.rect(newCube.x, newCube.y, newCube.w, newCube.h);
- canvasId.fill();
- canvasId.closePath();
- cubes.push(newCube);
- }
- console.log(cubes);
- const handler = (mouse) => {
- canvasId.lineTo(mouse.x, mouse.y);
- canvasId.stroke();
- }
- canvas.addEventListener('click', function(evt){
- mouse = mouse_player1(evt, canvas);
- cubes.forEach((item) => {
- canvasId.beginPath();
- canvasId.rect(item.x, item.y, item.w, item.h);
- canvasId.closePath();
- if(canvasId.isPointInPath(mouse.x, mouse.y)){
- activeColor = item.color;
- isActive = true;
- }
- });
- if(!isActive){
- canvasId.beginPath();
- canvasId.strokeStyle = activeColor;
- canvasId.moveTo(mouse.x, mouse.y);
- canvas.addEventListener('mousemove', handler);
- isActive = true;
- } else {
- canvas.removeEventListener('mousemove', handler);
- isActive = false;
- canvasId.closePath();
- }
- });
- });
- 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
- }
- class ColorCube{
- constructor(x){
- this.x = x;
- this.y = 750;
- this.w = 50;
- this.h = 50;
- this.color = "rgb(" + Math.floor(Math.random()*255 + 1) + ", " + Math.floor(Math.random()*255 + 1) + ", " + Math.floor(Math.random()*255 + 1) + ")";
- }
- }
- </script>
- <style>
- canvas{
- background-color: black;
- }
- </style>
- </head>
- <body style="margin:0px;">
- <canvas width="800" height="800" id="canvasId"></canvas>
- </body>
- </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement