2

I'm trying to "draw" a rectangle in a black canvas but it doesn't work. This is my code:

window.onload = function() {
  canvas = document.getElementById('canvas');
  canvasContext = canvas.getContext('2d');

  draw();
}

function draw() {
  canvasContext.fillstyle='black';
  canvasContext.fillRect(0,0,800,600);
  canvasContext.fillstyle='white';
  canvasContext.fillRect(0,0,10,10);
}
<canvas id="canvas" width="800" height="600"></canvas>

Why doesn't it work?

5
  • 1
    Hello - what doesn't work specifically? Does it show anything? Commented Sep 4, 2017 at 17:09
  • 1
    It's not the problem, but: That code is falling prey to The Horror of Implicit Globals (that's a post on my anemic little blog). Declare your variables at the appropriate scope. In this case, I would probably remove the onload handler and instead just put all of your code in a scoping function in a script at the end of the HTML, right before the closing </body> tag. Commented Sep 4, 2017 at 17:11
  • canvasContext will not be accessible in draw function Commented Sep 4, 2017 at 17:11
  • 1
    @PranayKumar: Yes, it will (and is). Commented Sep 4, 2017 at 17:11
  • 1
    It's just a typo, fillstyle should be fillStyle (capital S). Voting to close as typo/non-repro. JavaScript is case-sensitive. Commented Sep 4, 2017 at 17:12

1 Answer 1

1

you have used lowercase "s" instead of uppercase "S" in fillstyle

Change

canvasContext.fillstyle

to

canvasContext.fillStyle

window.onload = function() {
  canvas = document.getElementById('canvas');
  canvasContext = canvas.getContext('2d');


  draw();

}

function draw() {
  canvasContext.fillStyle='black';
  canvasContext.fillRect(0,0,800,600);
  canvasContext.fillStyle='white';
  canvasContext.fillRect(0,0,100,100);


}
<canvas id="canvas" width="800" height="600"></canvas>

Sign up to request clarification or add additional context in comments.

4 Comments

Code dumps are not useful answers. Say what you changed, and why.
But moreover, typos don't need answers, just comments and (when you can) close votes. Posting an answer can prevent the OP deleting the question, which is the right course of action as it's not useful to others in the future (and could force them to accept rep loss from downvotes).
The time to explain is as you're writing the answer, not after posting it.
i am sorry friend, i am not an active stack overflow user dont know the rules much, just started answering questions a few weeks ago

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.