Not sure what is wrong. Seems the fillStyle doesn’t work. The color defined with it doesn’t render. Could somebody help? Thank you.
<body>
<canvas width="480" height="320">
</canvas>
<script>
let canvas = document.querySelector('canvas');
let ctx = canvas.getContext('2d');
let x = 50;
let y = 60;
let width = 100;
let height = 75;
let color = 'blue';
canvas.innerHTML= '';
ctx.fillRect(x, y, width, height);
ctx.fillStyle = color;
</script>
</body>
You are getting this problem because the fillStyle/strokeStyle/whatever has to be defined before you actually try to draw a shape. You set the color of what will be drawn next, and then you draw it. You don’t draw the shape and then set it to have a different color — 2D Canvas just doesn’t work like that. As soon as a shape is drawn on the canvas, it is static and unchangeable. When you see 2D Canvas animations/games, the entire scene is redrawn statically on every frame.
So if you move the ctx.fillStyle line to before the ctx.fillRect line, you’ll see the color applied to the rectangle.
Also, I’m not sure what canvas.innerHTML= ''; is doing - this doesn’t really make sense. If you want to clear the canvas before drawing, you have to draw a rectangle over the top of the whole canvas, the same color as the background, so for example: