【问题标题】:JavaScript: How to change the variable color of a object with a onClick functionJavaScript:如何使用 onClick 函数更改对象的可变颜色
【发布时间】:2020-05-17 22:13:06
【问题描述】:

我正在尝试制作一个可以使用 WASD 键进行绘图的小游戏。

Here is a JSFiddle 到目前为止我所拥有的。在代码中,你可以看到我做了一个碰撞函数,暂时忽略它。我不再需要它了。但我的问题是:是否有可能使有 3 个可点击的按钮可以改变立方体的颜色而无需重新加载页面?这样就有更多的颜色可以使用。我已经在网上搜索,看看是否能找到与我的问题相关的东西,所以我要在这里尝试。最重要的部分是我指定立方体颜色的部分。这是很多代码......另外,那里有一些荷兰语文本,因为英语不是我的母语。

(function(){ "use strict"

  var controller, display, game;

  controller = 
  {
      left: false,
      right:false,
      up: false,
      down: false,


      keyUpDown:function(event)
      { 
      var key_state = (event.type == "keydown")?true:false;

      switch(event.keyCode) 
      {
        case 65://links
          controller.left = key_state; break;     //dit is wasd, niet de pijltjes toetsen.
        case 87://jump  
          controller.up = key_state; break;
        case 68://rechts
          controller.right = key_state; break;
        case 83://naar beneden
          controller.down = key_state; break;
      }
    } 
  };

  //hier wordt alles gerenderd en er zit een resize functie bij.
  display = 
  {
      buffer:document.createElement("canvas").getContext("2d"),
      context:document.querySelector("canvas").getContext("2d"),
      output:document.querySelector("p"), 

  render:function()
  {
      for (let index = game.world.map.length - 1; index > -1; -- index)
      {
          this.buffer.fillStyle = (game.world.map[index] >1) ?("#0000" + game.world.map[index] + "100"): "#00000";

          this.buffer.fillRect((index % game.world.columns) 
          * game.world.tile_size, Math.floor(index / game.world.columns) * 
          game.world.tile_size,game.world.tile_size,game.world.tile_size);
      }

          this.buffer.fillStyle = game.player.color;
          this.buffer.fillRect(game.player.x, game.player.y, game.player.width, game.player.height);

          this.context.drawImage(this.buffer.canvas, 1,0, this.buffer.canvas.width, this.buffer.canvas.height, 0,0, this.context.canvas.width, this.context.canvas.height);
      },


  resize:function(event)
      {
          var client_h = document.documentElement.clientHeight;
          display.context.canvas.width = document.documentElement.clientWidth - 20;

          if(display.context.canvas.width > client_h)
          {
              display.context.canvas.width = client_h;
          }

          display.context.canvas.height = Math.floor(display.context.canvas.width * 0.625);

          display.render();
      }

  };

  game = {

  player:
  {
      color:"red",
      height: 10,
      width: 10,
      jumping: false,
      old_x:160,
      old_y:160,
      velocity_x: 0,
      velocity_y: 0,
      y:400,
      x:400,

  },



  world: //tile map ding elk getal stelt een blok voor in het spel
  {
      columns:10,
      rows:10,
      tile_size:100,

      map:
      [0,0,0,0,0,0,0,0,0,0,0,
       0,0,0,0,0,0,0,0,0,0,0,
       0,0,0,0,0,0,0,0,0,0,0,
       0,0,0,0,0,0,0,0,0,0,0,
       0,0,0,0,0,0,0,0,0,0,0,
       0,0,0,0,0,0,0,0,0,0,0,
       0,0,0,0,0,0,0,0,0,0,0,
       0,0,0,0,0,0,0,0,0,0,0,
       5,5,5,5,5,5,5,5,5,5,0]
          //tile map, elk getal is een blokje in het spel, deze moet nog groter en hoger  

  },

  //de collision voor alle soorten blokken, 0 is namelijk niks.
  // Heel veel tijd in gestop, nooit gebruikt oops...
  collision:{
      1:function(object,row,column)//
      {
          if(this.topCollision(object,row)) {return;} //als geen top collision
          this.rightCollision(object,column);         //doe dan side collision
      },

      2:function(object,row,column)//heeft top en left collision
      {
          if(this.topCollision(object,row)){return;}
          this.leftCollision(object, column);
      },

      3:function(object,row,column)//alleen rechts collision
      {
          this.rightCollision(object,column);
      },

      4:function(object,row,column)//heeft overal collision behalve onder
      {
          if(this.topCollision(object, row)) {return;}
          if (this.leftCollision(object, column)){return;}
          this.rightCollision(object, column);
      },

      5:function(object,row, column)//alleen collision als player door de top valt
      {
          this.topCollision(object, row);
      },


      leftCollision(object, column)
      {
          if (object.velocity_x > 0) {    

          var left = column * game.world.tile_size;

          if (object.x + object.width * 0.5 > left && object.old_x <= left) {

          object.velocity_x = 0;//stop
          object.x = object.old_x = left - object.width * 0.5 - 0.001;
              return true;
          }
      }
      return false;

      },

      rightCollision(object, column)
      {
      if (object.velocity_x < 0)
      {
          var right = (column + 1) * game.world.tile_size;
          if (object.x + object.width *0.5 < right && object.old_x + object.width * 0.5 >= right)
          {
              object.velocity_x = 0;
              object.old_x = object.x = right - object.width * 0.5;
              return true;
          }
      }
      return false;
      },

      topCollision(object, row)
      {
      if (object.velocity_y > 0)
      {
          var top = row * game.world.tile_size;
          if(object.y + object.height > top && object.old_y + object.height <= top)
          {
              object.jumping = false;
              object.velocity_y = 0;
              object.old_y = object.y = top - object.height - 0.01;
              return true;
          }
      }
      return false;

      }
  },

  loop:function(){

      if(controller.left)
      {
          game.player.velocity_x -=0.8;
      }

      if(controller.right)
      {
          game.player.velocity_x +=0.8;
      }
      if(controller.up )
      {
          game.player.velocity_y -= 0.8;

      }
      if(controller.down )
      {
          game.player.velocity_y +=0.8;

      }



      game.player.old_x = game.player.x;  //opslaan laatste positie van player
      game.player.old_y = game.player.y;  //dat is voor het de collision

      game.player.x += game.player.velocity_x;
      game.player.y += game.player.velocity_y;

      if (game.player.x < 0)
      {
          game.player.velocity_x = 0;
          game.player.old_x = game.player.x = 0;
      } else if(game.player.x + game.player.width > display.buffer.canvas.width)
          {
              game.player.velocity_x = 0;
              game.player.old_x = game.player.x = display.buffer.canvas.width - game.player.width;
          }

      if (game.player.y < 0)
      {
          game.player.velocity_y = 0;
          game.player.old_y = game.player.y = 0;
      } else if(game.player.y + game.player.height > display.buffer.canvas.height)
          {
              game.player.velocity_y = 0;
              game.player.old_y = game.player.y = display.buffer.canvas.height - game.player.height;
          }


      //doe berekeningen voor de x en y tile positie in de map.
      var tile_x = Math.floor((game.player.x + game.player.width * 0.5) / game.world.tile_size);
      var tile_y = Math.floor((game.player.y + game.player.height) / game.world.tile_size);
      //value at index probeert de positie te verkijgen van de tile in de map.  
      var value_at_index = game.world.map[tile_y * game.world.columns + tile_x];





      if (value_at_index != 0)
      {
          game.collision[value_at_index](game.player, tile_y, tile_x);
      }

      tile_x = Math.floor((game.player.x + game.player.width * 0.5) / game.world.tile_size);
      tile_y = Math.floor((game.player.y + game.player.height) / game.world.tile_size);
      value_at_index = game.world.map[tile_y * game.world.columns + tile_x];

      if (value_at_index != 0)
      {
          game.collision[value_at_index](game.player, tile_y, tile_x);
      }


      game.player.velocity_x *=0.9; //wrijving
      game.player.velocity_y *=0.9;
      // je doet dit er na omdat je niet dat het wordt veranderd door de collision functie.



      display.render();

      window.requestAnimationFrame(game.loop);

  }
  };

  //groote van canvas enz.

  display.buffer.canvas.height = 800;
  display.buffer.canvas.width = 800;

  window.addEventListener("resize", display.resize);
  window.addEventListener("keydown", controller.keyUpDown);
  window.addEventListener("keyup", controller.keyUpDown);

  display.resize();

  game.loop();

})();      
<!DOCTYPE html>
    <html>
    <head>
        <title>Super epic game</title>
        <link rel="stylesheet" type="text/css" href="mainstyles.css">
        <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
        <link href="https://fonts.googleapis.com/css?family=Lato:300&display=swap" rel="stylesheet">
    </head>
    
    <body>
    <canvas id="canvas" style="background-color: black;"></canvas>    
    <input type="button" id="reset" value="Reset drawing" onClick="window.location.reload()">
    
    <p id="main">Hello! Use the WASD keys to move around and draw :)!</p>
    
    
    
    
    </body>
    </html>

【问题讨论】:

  • 修改game.player.color 有效。你试过吗?
  • 另外,为什么你在按钮上使用&lt;input&gt; 元素而不是普通的&lt;button&gt; 元素?

标签: javascript html variables colors


【解决方案1】:

我已经修改了您的代码以包含 3 个按钮,这些按钮可以在不刷新页面的情况下更改正方形的颜色。 JavaScript 为每个按钮分配一个事件侦听器,并在单击其中一个时进行侦听;单击按钮时,正方形的颜色将更改为单击按钮的data-color 属性中的任何值。代码通过修改game.player.color改变颜色。

jsfiddle

* {
  margin: 0;
  padding: 0;
}

canvas {
  background-color: black;
  height: 800px;
  width: 800px;
  display: block;
  margin-left: auto;
  margin-right: auto;
  /*deze staat in het midden als het goed is*/
}

#reset {
  margin-left: auto;
  margin-right: auto;
  display: block;
  font-family: Lato;
}

#main {
  margin-left: auto;
  margin-right: auto;
  text-align: center;
  font-family: Lato;
  margin-top: auto;
}
<!DOCTYPE html>
<html>

<head>
  <title>Super epic game</title>
  <link rel="stylesheet" type="text/css" href="mainstyles.css">
  <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
  <link href="https://fonts.googleapis.com/css?family=Lato:300&display=swap" rel="stylesheet">
</head>

<body>
  <canvas id="canvas" style="background-color: black;"></canvas>
  <input type="button" id="reset" value="Reset drawing" onClick="window.location.reload()">
  <button class="color-changer" data-color="red">Red</button>
  <button class="color-changer" data-color="green">Green</button>
  <button class="color-changer" data-color="blue">Blue</button>

  <p id="main">Hello! Use the WASD keys to move around and draw :)</p>




  <script>
    const container = (function() {
      "use strict"

      var controller, display, game;

      controller = {
        left: false,
        right: false,
        up: false,
        down: false,


        keyUpDown: function(event) {
          var key_state = (event.type == "keydown") ? true : false;

          switch (event.keyCode) {
            case 65: //links
              controller.left = key_state;
              break; //dit is wasd, niet de pijltjes toetsen.
            case 87: //jump  
              controller.up = key_state;
              break;
            case 68: //rechts
              controller.right = key_state;
              break;
            case 83: //naar beneden
              controller.down = key_state;
              break;
          }
        }
      };



      //hier wordt alles gerenderd en er zit een resize functie bij.
      display = {
        buffer: document.createElement("canvas").getContext("2d"),
        context: document.querySelector("canvas").getContext("2d"),
        output: document.querySelector("p"),

        render: function() {
          for (let index = game.world.map.length - 1; index > -1; --index) {
            this.buffer.fillStyle = (game.world.map[index] > 1) ? ("#0000" + game.world.map[index] + "100") : "#00000";

            this.buffer.fillRect((index % game.world.columns) *
              game.world.tile_size, Math.floor(index / game.world.columns) *
              game.world.tile_size, game.world.tile_size, game.world.tile_size);
          }

          this.buffer.fillStyle = game.player.color;
          this.buffer.fillRect(game.player.x, game.player.y, game.player.width, game.player.height);

          this.context.drawImage(this.buffer.canvas, 1, 0, this.buffer.canvas.width, this.buffer.canvas.height, 0, 0, this.context.canvas.width, this.context.canvas.height);
        },


        resize: function(event) {
          var client_h = document.documentElement.clientHeight;
          display.context.canvas.width = document.documentElement.clientWidth - 20;

          if (display.context.canvas.width > client_h) {
            display.context.canvas.width = client_h;
          }

          display.context.canvas.height = Math.floor(display.context.canvas.width * 0.625);

          display.render();
        }

      };

      game = {

        player: {
          color: "red",
          height: 10,
          width: 10,
          jumping: false,
          old_x: 160,
          old_y: 160,
          velocity_x: 0,
          velocity_y: 0,
          y: 400,
          x: 400
        },



        world: //tile map ding elk getal stelt een blok voor in het spel
        {
          columns: 10,
          rows: 10,
          tile_size: 100,

          map: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
            5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 0
          ]
          //tile map, elk getal is een blokje in het spel, deze moet nog groter en hoger  

        },

        //de collision voor alle soorten blokken, 0 is namelijk niks.
        // Heel veel tijd in gestop, nooit gebruikt oops...
        collision: {
          1: function(object, row, column) //
          {
            if (this.topCollision(object, row)) {
              return;
            } //als geen top collision
            this.rightCollision(object, column); //doe dan side collision
          },

          2: function(object, row, column) //heeft top en left collision
          {
            if (this.topCollision(object, row)) {
              return;
            }
            this.leftCollision(object, column);
          },

          3: function(object, row, column) //alleen rechts collision
          {
            this.rightCollision(object, column);
          },

          4: function(object, row, column) //heeft overal collision behalve onder
          {
            if (this.topCollision(object, row)) {
              return;
            }
            if (this.leftCollision(object, column)) {
              return;
            }
            this.rightCollision(object, column);
          },

          5: function(object, row, column) //alleen collision als player door de top valt
          {
            this.topCollision(object, row);
          },


          leftCollision(object, column) {
            if (object.velocity_x > 0) {

              var left = column * game.world.tile_size;

              if (object.x + object.width * 0.5 > left && object.old_x <= left) {

                object.velocity_x = 0; //stop
                object.x = object.old_x = left - object.width * 0.5 - 0.001;
                return true;
              }
            }
            return false;

          },

          rightCollision(object, column) {
            if (object.velocity_x < 0) {
              var right = (column + 1) * game.world.tile_size;
              if (object.x + object.width * 0.5 < right && object.old_x + object.width * 0.5 >= right) {
                object.velocity_x = 0;
                object.old_x = object.x = right - object.width * 0.5;
                return true;
              }
            }
            return false;
          },

          topCollision(object, row) {
            if (object.velocity_y > 0) {
              var top = row * game.world.tile_size;
              if (object.y + object.height > top && object.old_y + object.height <= top) {
                object.jumping = false;
                object.velocity_y = 0;
                object.old_y = object.y = top - object.height - 0.01;
                return true;
              }
            }
            return false;

          }
        },

        loop: function() {

          if (controller.left) {
            game.player.velocity_x -= 0.8;
          }

          if (controller.right) {
            game.player.velocity_x += 0.8;
          }
          if (controller.up) {
            game.player.velocity_y -= 0.8;

          }
          if (controller.down) {
            game.player.velocity_y += 0.8;

          }



          game.player.old_x = game.player.x; //opslaan laatste positie van player
          game.player.old_y = game.player.y; //dat is voor het de collision

          game.player.x += game.player.velocity_x;
          game.player.y += game.player.velocity_y;

          if (game.player.x < 0) {
            game.player.velocity_x = 0;
            game.player.old_x = game.player.x = 0;
          } else if (game.player.x + game.player.width > display.buffer.canvas.width) {
            game.player.velocity_x = 0;
            game.player.old_x = game.player.x = display.buffer.canvas.width - game.player.width;
          }

          if (game.player.y < 0) {
            game.player.velocity_y = 0;
            game.player.old_y = game.player.y = 0;
          } else if (game.player.y + game.player.height > display.buffer.canvas.height) {
            game.player.velocity_y = 0;
            game.player.old_y = game.player.y = display.buffer.canvas.height - game.player.height;
          }


          //doe berekeningen voor de x en y tile positie in de map.
          var tile_x = Math.floor((game.player.x + game.player.width * 0.5) / game.world.tile_size);
          var tile_y = Math.floor((game.player.y + game.player.height) / game.world.tile_size);
          //value at index probeert de positie te verkijgen van de tile in de map.  
          var value_at_index = game.world.map[tile_y * game.world.columns + tile_x];





          if (value_at_index != 0) {
            game.collision[value_at_index](game.player, tile_y, tile_x);
          }

          tile_x = Math.floor((game.player.x + game.player.width * 0.5) / game.world.tile_size);
          tile_y = Math.floor((game.player.y + game.player.height) / game.world.tile_size);
          value_at_index = game.world.map[tile_y * game.world.columns + tile_x];

          if (value_at_index != 0) {
            game.collision[value_at_index](game.player, tile_y, tile_x);
          }


          game.player.velocity_x *= 0.9; //wrijving
          game.player.velocity_y *= 0.9;
          // je doet dit er na omdat je niet dat het wordt veranderd door de collision functie.



          display.render();

          window.requestAnimationFrame(game.loop);

        }
      };

      //groote van canvas enz.

      display.buffer.canvas.height = 800;
      display.buffer.canvas.width = 800;

      window.addEventListener("resize", display.resize);
      window.addEventListener("keydown", controller.keyUpDown);
      window.addEventListener("keyup", controller.keyUpDown);

      display.resize();

      game.loop();

      var colorChangers = document.getElementsByClassName("color-changer");
      var colorChangersLength = colorChangers.length;
      for (let x = 0; x < colorChangersLength; x++) {
        colorChangers[x].addEventListener("click", function() {
          game.player.color = colorChangers[x].getAttribute("data-color");
        });
      }

    })();
  </script>




</body>

</html>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-25
    • 2019-05-03
    • 1970-01-01
    • 2017-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-15
    相关资源
    最近更新 更多