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");
- let mouse;
- let cubes = [];
- let activeColor = 'red';
- let activeState = false;
- for (let i = 1; i <= 10; i++) {
- let newCube = new ColorCube(canvas.width - 50*i - 10*i, canvas.height - 50, 50, 50);
- context.beginPath();
- context.fillStyle = newCube.color;
- context.rect(newCube.x, newCube.y, newCube.width, newCube.height);
- context.fill();
- context.closePath();
- cubes.push(newCube);
- }
- console.log(cubes);
- const handler = (evt) => {
- mouse = mousePlayer1(evt);
- context.strokeStyle = activeColor;
- context.lineTo(mouse.x, mouse.y);
- context.stroke();
- }
- canvas.addEventListener('click', (e) => {
- mouse = mousePlayer1(e);
- cubes.forEach(item => {
- context.beginPath();
- context.rect(item.x, item.y, item.width, item.height);
- context.closePath();
- if(context.isPointInPath(mouse.x, mouse.y)){
- activeColor = item.color;
- }
- });
- if(!activeState){
- context.beginPath();
- context.moveTo(mouse.x, mouse.y);
- canvas.addEventListener('mousemove', handler);
- activeState = true;
- } else {
- canvas.removeEventListener('mousemove', handler);
- activeState = false;
- }
- });
- });
- const mousePlayer1 = (e) => {
- return {
- x: e.layerX,
- y: e.layerY,
- }
- }
- const colorPicker = () => {
- let color = '#';
- let hex = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'];
- for (let i = 0; i < 6; i++) {
- color = color + hex[Math.floor(Math.random()*16)];
- }
- return color;
- }
- class ColorCube{
- constructor(x, y, width, height){
- this.x = x;
- this.y = y;
- this.width = width;
- this.height = height;
- this.color = colorPicker();
- }
- }
- </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