首页 > 解决方案 > 使用 js 绘图 - fillstyle 仅适用于十六进制值

问题描述

当我分配一个十六进制颜色值时,我只能让 fillstyle 工作。当我尝试其他使用填充样式的方法时,我只是得到一个黑盒子。我需要将 RGB 值作为变量传递。希望有人能告诉我我错过了什么这是一个片段:

<!DOCTYPE html>
<html>
<body>
<p>Canvas:</p>
<canvas id="DrawQuote" width="300" height="300" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
<br><br>

<button onclick="draw()">Draw</button>    

<script>
function draw() {
  var c = document.getElementById("DrawQuote");
  var ctx = c.getContext("2d");
  ctx.clearRect(0, 0, c.width, c.height); 

  WallColour = "ES";
  switch (WallColour) {
    case "BL": Rwall = 25;  Gwall = 25;  Bwall = 25; break;
    case "ES": Rwall = 154; Gwall = 121; Bwall = 78; break;
    default:
    Rwall = 255; Gwall = 255; Bwall = 255; break;
  }

    // draw box
ctx.fillStyle = "#FF0000";    // only one that works

//  doesn't work THIS IS THE ONE I NEED
//  ctx.fillstyle = "rgb(" + Rwall + ", " + Gwall + ", " + Bwall + ")";

//  doesn't work (rgb or hex)
//  var col = "rgb(44,66,77)";
//  var col = "#FF0000";
//  ctx.fillstyle = col;

//  doesn't work
//  ctx.fillstyle = "rgb(99, 99, 99)";

ctx.fillRect(0, 0, 150, 100);


}
</script>

<p><strong>The End</strong></p>

</body>
</html>

标签: javascript

解决方案


使用fillStyle代替fillstyle

function draw() {
  var c = document.getElementById("DrawQuote");
  var ctx = c.getContext("2d");
  ctx.clearRect(0, 0, c.width, c.height); 

  WallColour = "ES";
  switch (WallColour) {
    case "BL": Rwall = 25;  Gwall = 25;  Bwall = 25; break;
    case "ES": Rwall = 154; Gwall = 121; Bwall = 78; break;
    default:
    Rwall = 255; Gwall = 255; Bwall = 255; break;
  }


  ctx.fillStyle = "rgb(" + Rwall + ", " + Gwall + ", " + Bwall + ")";



ctx.fillRect(0, 0, 150, 100);


}
<p>Canvas:</p>
<canvas id="DrawQuote" width="300" height="300" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
<br><br>

<button onclick="draw()">Draw</button>    
<p><strong>The End</strong></p>


推荐阅读