Ask coding questions

← Back to all posts
context.fillStyle is not a function at createRectangle error
AJDevelopment (151)

I am trying to write a function that creates rectangles, but I keep getting the same error.

My code I wrote is:

engine.js

var canvas = document.querySelector("canvas");
var context = document.querySelector("canvas").getContext("2d");

function createRectangle(x, y, w, h, fill) {
    context.fillStyle(fill);
    context.fillRect(x, y, w, h);
}

createRectangle(10, 10, 100, 50, "#C0FFEE");

How do I fix this error?

Answered by xxpertHacker (861) [earned 5 cycles]
View Answer
Comments
hotnewtop
xxpertHacker (861)

I misinterpreted MDN's docs on this, CanvasRenderingContext2D#fillStyle is a setter, not a function.

This worked fine for me:

const canvas = document.querySelector("canvas");
const context = canvas.getContext("2d");

function createRectangle(x, y, w, h, fill) {
	context.fillStyle = fill;
	context.fillRect(x, y, w, h);
}

createRectangle(10, 10, 100, 50, "#C0FFEE");
AJDevelopment (151)

@xxpertHacker oh ok turns out i thought fillStyle was a function

xxpertHacker (861)

@AJDevelopment Hate to ask, but can you accept the answer?

xxpertHacker (861)

What browser are you using, and what version?

xxpertHacker (861)

@AJDevelopment Odd, if you were using an old browser, I wouldn't expect them to exist, but you aren't.

I'm on mobile rn, but I'll check on a desktop in ~30 minutes.