Home > Net >  Mission with Javascript :)
Mission with Javascript :)

Time:06-23

Good afternoon everyone, I have a problem with javascript.

I was assigned as a task to make a box that changes color when clicking on the page, I was doing my code but I managed to make the box but not change color.

I use Eventlistener because i want to repeat the change color.

Idk what is bad in my code i see alot of forums but nothing help.

I hope you can help me, thanks

<!DOCTYPE html>
<meta charset="utf-8">

<html><head>
  <title> Cuadro cambia color // By Abraham Gonzalez </title>
</head>

<script>


  function myBody(){
      var myBody;
      myBody = document.getElementById("myBody");
      myBody.addEventListener("click", btnRojoClic)
      ctx.fillStyle = rgb[Math.floor(Math.random() * 255)];
      
  }

  function btnRojoClic(){
    var myBody;
    myBody = document.getElementById("myBody")
    myBody.style.color = "red"

  }
  
</script>

<body id="myBody"> 

 <canvas id="canvas" width="400" height="400"></canvas>
 <script>



 var canvas = document.getElementById("canvas");
 var ctx = canvas.getContext("2d");


  
 var posicion = 0;    
 var tamano = 0;
    
 setInterval(function () {
    ctx.clearRect(0, 0, 400, 400);
    ctx.fillRect(posicion,0 , tamano, tamano);
    
    posicion  ;
    tamano  ;
    
    if (posicion > 400){
        posicion = 0;
        tamano = 0;
    }
}, 30);



</script></body></html>

 


 

CodePudding user response:

There were three problems I found:

  • myBody() was never called
  • you said myBody.style.color = "red" but should be ctx.fillStyle = "red"
  • rgb list is not defined.

Here is the fixed code without the rgb list (I took the random hexadecimal code from @RasAlGhul):

<!DOCTYPE html>
<html>
    <head>
        <title> Cuadro cambia color // By Abraham Gonzalez </title>
        <meta charset="utf-8">
    </head>
    <body id="myBody" onl oad="myBody()">


        <canvas id="canvas" width="400" height="400"></canvas>
        <script>

            
            function myBody() {
                var myBody;
                myBody = document.getElementById("myBody");
                myBody.addEventListener("click", btnRojoClic)
                ctx.fillStyle = "#" Math.floor(Math.random()*16777215).toString(16);

            }

            function btnRojoClic() {
                var myBody;
                myBody = document.getElementById("myBody")
                ctx.fillStyle = "red" 

            }


            var canvas = document.getElementById("canvas");
            var ctx = canvas.getContext("2d");
            var posicion = 0;
            var tamano = 0;

            setInterval(function () {
                ctx.clearRect(0, 0, 400, 400);
                ctx.fillRect(posicion, 0, tamano, tamano);

                posicion  ;
                tamano  ;

                if (posicion > 400) {
                    posicion = 0;
                    tamano = 0;
                }
            }, 30);
        </script>
    </body>

</html>

CodePudding user response:

Some things werent correct:

  • You never calling myBody()
  • myBody was a function and a var
  • rgb was undefined
<meta charset="utf-8" />

<html>
  <head>
    <title>Cuadro cambia color // By Abraham Gonzalez</title>
  </head>

  <body id="myBody">
    <canvas id="canvas" width="400" height="400"></canvas>
  </body>

  <script>
    function myBody() {
      var myBodyt = document.getElementById('myBody');
      myBodyt.addEventListener('click', btnRojoClic);
    }

    function btnRojoClic() {
      console.log('clickkeked');
      var canvas = document.getElementById('canvas');
      var ctx = canvas.getContext('2d');
      ctx.fillStyle = "#" Math.floor(Math.random()*16777215).toString(16);
    }

    myBody();
    var canvas = document.getElementById('canvas');
    var ctx = canvas.getContext('2d');

    var posicion = 0;
    var tamano = 0;

    setInterval(function () {
      ctx.clearRect(0, 0, 400, 400);
      ctx.fillRect(posicion, 0, tamano, tamano);

      posicion  ;
      tamano  ;

      if (posicion > 400) {
        posicion = 0;
        tamano = 0;
      }
    }, 30);
  </script>
</html>

Edit only change color when the square is clicked. You cannot add an event listener directly on the rectangle (fillRect) but you can do it on the canvas. When there's a click, check if the event click position (x,y) is on the square (checkCollision ()) . If so change the color. Note: the square() isn't necessary and can be replaced by a class the functions (specially render) inside square() are responsible to draw the rect with the given context.

    <!DOCTYPE html>
<meta charset="utf-8" />

<html>
  <head>
    <title>Cuadro cambia color // By Abraham Gonzalez</title>
  </head>

  <body id="myBody">
    <canvas id="canvas" width="400" height="400"></canvas>
  </body>

  <script>
    function btnRojoClic() {
      var canvas = document.getElementById('canvas');
      var ctx = canvas.getContext('2d');
      ctx.fillStyle = '#'   Math.floor(Math.random() * 16777215).toString(16);
    }
    // you cann also use a class instead, the main idea is to check if the click event position was on the square surface. 
    function square() {
      let position = 0;
      let tamano = 0;
      const increasePosition = () => {
        position;
      };
      const increaseSize = () => {
        tamano  ;
      };
      const getPosition = () => {
        return position;
      };
      const getTamano = () => {
        return tamano;
      };
      const reset = () => {
        position = 0;
        tamno = 0;
      };
      const move = () => {
        increasePosition();
        increaseSize();
        if (position > 400) {
          reset();
        }
      };
      const render = (context) => {
        ctx.fillRect(position, 0, tamano, tamano);
      };
      return {
        move,
        render,
        getPosition,
        getTamano,
        reset
      };
    }
    /**
     * Get cursor position relativly to canvas 
     */
    const getCursorPosition = (canvas, event) => {
      const rect = canvas.getBoundingClientRect();
      const x = event.clientX - rect.left;
      const y = event.clientY - rect.top;
      return { x, y };
    };
    /**
     * Check if there is a collision (click position overlap square position) 
     * */
    const checkCollision = (canvas, ev, square) => {
      const { x, y } = getCursorPosition(canvas, ev);
      if (
        x >= square.getPosition() &&
        x <= square.getPosition()   square.getTamano() &&
        y >= square.getPosition() &&
        y <= square.getPosition()   square.getTamano()
      ) {
        canvas.getContext('2d').fillStyle =
          '#'   Math.floor(Math.random() * 16777215).toString(16);
      }
    };

    mySquare = square();

    var canvas = document.getElementById('canvas');
    var ctx = canvas.getContext('2d');
    canvas.addEventListener('click', (ev) =>
      checkCollision(canvas, ev, mySquare)
    );

    setInterval(function () {
      ctx.clearRect(0, 0, 400, 400);
      mySquare.move();
      mySquare.render();
    }, 30);
  </script>
</html>
  • Related