M Masood
M Masood

Reputation: 167

Canvas portion of function won't run?

changeCanvasBackground = function() {
  document.getElementById("ji").innerHTML = "Paragraph changed!";
  var canvas = document.getElementById('myCanvas');
  document.getElementById("ji").innerHTML = "Paragraph changed two!";
  var ctx = canvas.getContext('2D');
  ctx.fillStyle("Red");
}
document.addEventListener('DOMContentLoaded', changeCanvasBackground);
<p id="ji">Hello</p>
<div id="gameArea">
  <canvas id="myCanvas" width="800" height="480"></canvas>
</div>

The 'changeCanvasBackground' function does run, but the canvas portion does not, 'document.getElementById("ji")' is there to show this. If any one can help me out .

Upvotes: 0

Views: 33

Answers (1)

Get Off My Lawn
Get Off My Lawn

Reputation: 36311

  • getContext takes lower case characters 2d
  • You need to call fillRect after fillStyle
  • fillStyle is a property and not a method

So the three lines should look like this:

var ctx = canvas.getContext('2d');
ctx.fillStyle = "Red";
ctx.fillRect(0, 0, canvas.width, canvas.height);

The final result will be like so:

changeCanvasBackground = function() {
  document.getElementById("ji").innerHTML = "Paragraph changed!";
  var canvas = document.getElementById('myCanvas');
  document.getElementById("ji").innerHTML = "Paragraph changed two!";
  var ctx = canvas.getContext('2d');
  ctx.fillStyle = "Red";
  ctx.fillRect(0, 0, canvas.width, canvas.height);
}
document.addEventListener('DOMContentLoaded', changeCanvasBackground);
<p id="ji">Hello</p>
<div id="gameArea">
  <canvas id="myCanvas" width="800" height="480"></canvas>
</div>

Upvotes: 2

Related Questions