zenitsu
zenitsu

Reputation: 1

Can't draw on canvas .What could be the problem?

I am trying to draw something very basic to my canvas but its not drawing anything neither showing any errors to fix. what could be the issue here ?

Here's my code :

I also tried moving the js code to an external js file but did't work.

<body>
<canvas
  id="myCanvas"
  width="800"
  height="500"
  style="border:1px solid #474747;"
></canvas>

<script>
  var canvas = document.getElementById("myCanvas");
  var ctx = canvas.getContext("2d");
  ctx.fillStyle = "#FF0000";
  ctx.fillRect = (10, 100, 15, 400);
</script>

Upvotes: 0

Views: 266

Answers (2)

symlink
symlink

Reputation: 12209

ctx.fillRect = (10, 100, 15, 400); <-- fillRect() is a function, you're using it as an expression.

  var canvas = document.getElementById("myCanvas");
  var ctx = canvas.getContext("2d");
  ctx.fillStyle = "#FF0000";
  ctx.fillRect(10, 100, 15, 400);
<canvas
  id="myCanvas"
  width="800"
  height="500"
  style="border:1px solid #474747;"
></canvas>

Upvotes: 0

Nick Parsons
Nick Parsons

Reputation: 50694

Your issue is with:

ctx.fillRect = (10, 100, 15, 400);

.fillRect() is a method which takes a x, y, width, height as it parameters, so you need to call it like so:

ctx.fillRect(10, 100, 15, 400);

See example below:

var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.fillStyle = "#FF0000";
ctx.fillRect(10, 100, 15, 400);
<canvas id="myCanvas" width="800" height="500" style="border:1px solid #474747;"></canvas>

Upvotes: 1

Related Questions