简体   繁体   中英

Javascript script doesn't load in HTML

<!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.

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.

  • 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();
  • In your case you don't need 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> 

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM