'Drawing with js - fillstyle only works with hex value
I can only get fillstyle to work when I assign a hex color value. When I try other ways to use fillstyle I just get a black box. I need to pass RGB values as variables. Hopefully someone can tell me what am I missing Here is a snip:
<!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>
Solution 1:[1]
Use fillStyle instead of 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>
Solution 2:[2]
Actually, (after changing capitalization to fillStyle) you'd just need to wrap rgb in tildes ` and call the vars through it. quotations don't work here. And I know this is years old, but first thing I found. hopefully no one else needs to search for a while like I did long ago
// THIS IS THE ONE I NEED
ctx.fillStyle = `rgb( $(R),$(G),$(B) )`;
so just to clarify
Rwall = 255; Gwall = 255; Bwall = 255; break;
ctx.fillstyle = rgb( $(Rwall),$(Gwall),$(Bwall) );
or if you wanted to hardcode for whatever reason
ctx.fillstyle = rgb( 255,255,255 );
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Observer |
| Solution 2 | Trevor |
