简体   繁体   English

如何更改 canvas 中 Html 元素的颜色?

[英]How do I change a color of a Html element in a canvas?

I have made a post on this before however, it was not in a canvas, but when you try to apply this to a canvas It gives an error along the lines of Cant change the color of undefined so I thought it was an error of the way I defined it so I would add it to a class then run it as changing the color of all elements in the class, but when I try it the canvas just disappears.. but getting to the point is there an easy way to change the color of a HTML element in a canvas or am I just crazy但是,我之前已经对此发表过帖子,它不在 canvas 中,但是当您尝试将其应用于 canvas 时,它给出了一个错误,类似于 Cant change the color of undefined 所以我认为这是我定义它的方式,所以我将它添加到 class 然后运行它来改变 class 中所有元素的颜色,但是当我尝试它时,canvas 只是消失了。 canvas 中 HTML 元素的颜色还是我疯了

Code代码

 var myGamePiece = el.classList.add("class1"); var myObstacles = []; var myScore; function startGame() { myGamePiece = new component(30, 30, "red", 10, 120); myGamePiece.gravity = 0.05; myScore = new component("30px", "Consolas", "black", 280, 40, "text"); myGameArea.start(); } var myGameArea = { canvas: document.createElement("canvas"), start: function() { this.canvas.width = 480; this.canvas.height = 270; this.context = this.canvas.getContext("2d"); document.body.insertBefore(this.canvas, document.body.childNodes[0]); this.frameNo = 0; this.interval = setInterval(updateGameArea, 20); }, clear: function() { this.context.clearRect(0, 0, this.canvas.width, this.canvas.height); } } function component(width, height, color, x, y, type) { this.type = type; this.score = 0; this.width = width; this.height = height; this.speedX = 0; this.speedY = 0; this.x = x; this.y = y; this.gravity = 0; this.gravitySpeed = 0; this.update = function() { ctx = myGameArea.context; if (this.type == "text") { ctx.font = this.width + " " + this.height; ctx.fillStyle = color; ctx.fillText(this.text, this.x, this.y); } else { ctx.fillStyle = color; ctx.fillRect(this.x, this.y, this.width, this.height); } } this.newPos = function() { this.gravitySpeed += this.gravity; this.x += this.speedX; this.y += this.speedY + this.gravitySpeed; this.hitBottom(); } this.hitBottom = function() { var rockbottom = myGameArea.canvas.height - this.height; if (this.y > rockbottom) { this.y = rockbottom; this.gravitySpeed = 0; } } this.crashWith = function(otherobj) { var myleft = this.x; var myright = this.x + (this.width); var mytop = this.y; var mybottom = this.y + (this.height); var otherleft = otherobj.x; var otherright = otherobj.x + (otherobj.width); var othertop = otherobj.y; var otherbottom = otherobj.y + (otherobj.height); var crash = true; if ((mybottom < othertop) || (mytop > otherbottom) || (myright < otherleft) || (myleft > otherright)) { crash = false; } return crash; } } function updateGameArea() { var x, height, gap, minHeight, maxHeight, minGap, maxGap; for (i = 0; i < myObstacles.length; i += 1) { if (myGamePiece.crashWith(myObstacles[i])) { return; } } myGameArea.clear(); myGameArea.frameNo += 1; if (myGameArea.frameNo == 1 || everyinterval(150)) { x = myGameArea.canvas.width; minHeight = 20; maxHeight = 200; height = Math.floor(Math.random() * (maxHeight - minHeight + 1) + minHeight); minGap = 50; maxGap = 200; gap = Math.floor(Math.random() * (maxGap - minGap + 1) + minGap); myObstacles.push(new component(10, height, "green", x, 0)); myObstacles.push(new component(10, x - height - gap, "green", x, height + gap)); } for (i = 0; i < myObstacles.length; i += 1) { myObstacles[i].x += -1; myObstacles[i].update(); } myScore.text = "SCORE: " + myGameArea.frameNo; myScore.update(); myGamePiece.newPos(); myGamePiece.update(); } function everyinterval(n) { if ((myGameArea.frameNo / n) % 1 == 0) { return true; } return false; } function accelerate(n) { myGamePiece.gravity = n; } function Test() { document.getElementsByClassName("class1").style.background = "yellow"; }
 canvas { border: 1px solid #d3d3d3; background-color: #f1f1f1; }.class1 {}
 <body onload="startGame()"> <button onmousedown="accelerate(-0.2)" onmouseup="accelerate(0.05)">ACCELERATE</button> <p> Credit To W3Schools.com </p> <button onclick="test">Click To Change Player's Color</button> </body>

The code starts with: var myGamePiece = el.classList.add("class1");代码开头为: var myGamePiece = el.classList.add("class1"); el is not defined but anyway myGamePiece needs to be a component as created in startGame, it is not an ordinary HTML element. el 没有定义,但无论如何 myGamePiece 需要是 startGame 中创建的组件,它不是普通的 HTML 元素。

It is the creation of that component that the color is set.设置颜色的是该组件的创建。 Currently the color is hardcoded as 'red'.目前颜色被硬编码为“红色”。 To change the color you need to set a variable, let's call it playerColor, and use that in the component creation call rather than 'red'.要更改颜色,您需要设置一个变量,我们称之为 playerColor,并在组件创建调用中使用它而不是“红色”。

You are using function test to set up a color so let's change the test function to do that, but you need to get that color set up before startGame otherwise the canvas will have the incorrect color for the piece (or no set color).您正在使用 function 测试来设置颜色,所以让我们更改测试 function 来执行此操作,但是您需要在 startGame 之前设置该颜色,否则 ZFCC790C72A86190DE1B549D0DDC6F 的颜色将不正确(或不正确的颜色 set5)。

var playersColor = "red"; //the default value if the player doesn't change it
var myGamePiece;
var myObstacles = [];
var myScore;

function startGame() {
  myGamePiece = new component(30, 30, playersColor, 10, 120);//use playersColor
  myGamePiece.gravity = 0.05;
  myScore = new component("30px", "Consolas", "black", 280, 40, "text");
  myGameArea.start();
}

var myGameArea = {
  canvas: document.createElement("canvas"),
  start: function() {
    this.canvas.width = 480;
    this.canvas.height = 270;
    this.context = this.canvas.getContext("2d");
    document.body.insertBefore(this.canvas, document.body.childNodes[0]);
    this.frameNo = 0;
    this.interval = setInterval(updateGameArea, 20);
  },
  clear: function() {
    this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
  }
}

function component(width, height, color, x, y, type) {
  this.type = type;
  this.score = 0;
  this.width = width;
  this.height = height;
  this.speedX = 0;
  this.speedY = 0;
  this.x = x;
  this.y = y;
  this.gravity = 0;
  this.gravitySpeed = 0;
  this.update = function() {
    ctx = myGameArea.context;
    if (this.type == "text") {
      ctx.font = this.width + " " + this.height;
      ctx.fillStyle = color;
      ctx.fillText(this.text, this.x, this.y);
    } else {
      ctx.fillStyle = color;
      ctx.fillRect(this.x, this.y, this.width, this.height);
    }
  }
  this.newPos = function() {
    this.gravitySpeed += this.gravity;
    this.x += this.speedX;
    this.y += this.speedY + this.gravitySpeed;
    this.hitBottom();
  }
  this.hitBottom = function() {
    var rockbottom = myGameArea.canvas.height - this.height;
    if (this.y > rockbottom) {
      this.y = rockbottom;
      this.gravitySpeed = 0;
    }
  }
  this.crashWith = function(otherobj) {
    var myleft = this.x;
    var myright = this.x + (this.width);
    var mytop = this.y;
    var mybottom = this.y + (this.height);
    var otherleft = otherobj.x;
    var otherright = otherobj.x + (otherobj.width);
    var othertop = otherobj.y;
    var otherbottom = otherobj.y + (otherobj.height);
    var crash = true;
    if ((mybottom < othertop) || (mytop > otherbottom) || (myright < otherleft) || (myleft > otherright)) {
      crash = false;
    }
    return crash;
  }
}

function updateGameArea() {
  var x, height, gap, minHeight, maxHeight, minGap, maxGap;
  for (i = 0; i < myObstacles.length; i += 1) {
    if (myGamePiece.crashWith(myObstacles[i])) {
      return;
    }
  }
  myGameArea.clear();
  myGameArea.frameNo += 1;
  if (myGameArea.frameNo == 1 || everyinterval(150)) {
    x = myGameArea.canvas.width;
    minHeight = 20;
    maxHeight = 200;
    height = Math.floor(Math.random() * (maxHeight - minHeight + 1) + minHeight);
    minGap = 50;
    maxGap = 200;
    gap = Math.floor(Math.random() * (maxGap - minGap + 1) + minGap);
    myObstacles.push(new component(10, height, "green", x, 0));
    myObstacles.push(new component(10, x - height - gap, "green", x, height + gap));
  }
  for (i = 0; i < myObstacles.length; i += 1) {
    myObstacles[i].x += -1;
    myObstacles[i].update();
  }
  myScore.text = "SCORE: " + myGameArea.frameNo;
  myScore.update();
  myGamePiece.newPos();
  myGamePiece.update();
}

function everyinterval(n) {
  if ((myGameArea.frameNo / n) % 1 == 0) {
    return true;
  }
  return false;
}

function accelerate(n) {
  myGamePiece.gravity = n;
}

function test() {
  playersColor = "yellow";
}

<body>
  <button onmousedown="accelerate(-0.2)" onmouseup="accelerate(0.05)">ACCELERATE</button>
  <p> Credit To W3Schools.com </p>
  <button onclick="test()">Click To Change Player's Color</button>
  <button onclick="startGame();">Click to start the game</button>
</body>

............................................................................... ..................................................... .....................................

Although the following errors are not fundamentally what is causing non-changing of the player's color, they contain some coding errors which it might be helpful to point out for the future.尽管以下错误从根本上不是导致播放器颜色不变的原因,但它们包含一些编码错误,可能有助于将来指出。

<button onclick="test">Click To Change Player's Color</button>
<script>
    function Test() {
         document.getElementsByClassName("class1").style.background = "yellow";
</script>

The onclick="test" does nothing - you may be confusing the structure element.onclick = test - which sets which function is run on the element being clicked - with the syntax for the onclick="test();" onclick="test" 什么都不做 - 你可能会混淆结构元素。onclick = test - 它设置在被点击的元素上运行哪个 function - 使用 onclick="test();" 的语法needed in the button element attributes.需要在按钮元素属性中。

A further error is that the function is called Test, not test.另一个错误是 function 被称为测试,而不是测试。 Javascript is case sensitive. Javascript 区分大小写。 Also you need to select the one element with class1, not retrieve a collection of such elements, so you can set its style (if that is useful, is it?).您还需要 select 具有 class1 的一个元素,而不是检索此类元素的集合,因此您可以设置其样式(如果这有用,是吗?)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM