Reputation: 351
<!DOCTYPE html>
<html>
<head>
<title>Breakout</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<canvas width="900" height="450" class="canvas"></canvas>
<script src="scripts/base.js"></script>
</body>
</html>
This is the index file
*{
margin: 0;
padding: 0;
}
.canvas{
background-color: #b7b7b7;
}
This is the CSS file
var canvas = document.getElementsByClassName('canvas');
var context = canvas.getContext('2d');
context.beginPath();
context.drawRect(20,30,50,40);
context.fillStyle("#0022ff");
context.fill();
context.endPath();
And the javascript file. I am trying to create a breakout game and I am following a tutorial from udemy. Unfortunately, it seems there is something wrong with this code, but I don't know what. I verified the code one thousand times and I haven't found anything.
Upvotes: 1
Views: 1220
Reputation: 31
Use fillRect instead of drawRect:
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.fillRect(20,30,50,40);
ctx.endPath();
</script>
Upvotes: 0
Reputation: 1915
var context = canvas.getContext('2d');
should be var context = canvas[0].getContext('2d');
because you're using document.getElementsByClassName
which will return a collection of all the elements with that class name. and you want the context of the first one.context.drawRect
should be context.rect
.context.fillStyle
is not a function it should be context.fillStyle = "#0022ff";
context.endPath();
should be context.closePath();
context.beginPath();
and context.closePath();
. context.rect
already creates the path.var canvas = document.getElementsByClassName('canvas');
var context = canvas[0].getContext('2d');
context.rect(20, 30, 50, 40);
context.fillStyle = "#0022ff";
context.fill();
* {
margin: 0;
padding: 0;
}
.canvas {
background-color: #b7b7b7;
}
<canvas width="900" height="450" class="canvas"></canvas>
Upvotes: 0
Reputation:
That's because in your var canvas
, you're calling document.getElementByClassName
which will return an "array-like" object. So, I'd suggest you to use IDs instead of selecting using a class.
Upvotes: 2