简体   繁体   中英

Simple Graphic won't show in the canvas

Learning HTML5 I came across a cookbook for graphing and data visualization. this is the first exercise and I can't get the graphic to show.

I tried so many things that I even copy and paste the source code to see if it worked, and it didn't D:

here is the code: index.html:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <script src="01.01.canvas.js"></script>
    <title>Canvas Example</title>
  </head>
  <body onLoad="init();" style="margin:0px">

    <canvas id="myCanvas"> </canvas>
  </body>
</html>

01.01.canvas.js:

function init()
{
    updateCanvas();
}

function  updateCanvas()
{
    //rest of the code in the next steps will go in here
    var width = window.innerWidth;
    var myCanvas = document.getElementById("myCanvas");
    myCanvas.width = width;
    myCanvas.height = height;
    var height = 100

    var context = myCanvas.getContext("2d");
        context.fillStyle = "#FCEAB8";
        context.fillRect(0,0,width,height);

    var circleSize=10;
    var gaps= circleSize+10;
    var widthCount = parseInt(width/gaps); 
    var heightCount = parseInt(height/gaps); 
    var aColors=["#43A9D1","#EFA63B","#EF7625","#5E4130"];
    var aColorsLength = aColors.length;

    for(var x=0; x<widthCount;x++){
        for(var y=0; y<heightCount;y++){
          context.fillStyle = aColors[parseInt(Math.random()*aColorsLength)];
          context.beginPath();
          context.arc(circleSize+gaps*x,circleSize+ gaps*y, circleSize, 0, Math.PI*2, true); 
          context.closePath();
          context.fill();   
        }
    }
}

I expected a rectangular block filled with dots of many colors showing in the canvas.

The issue here is that your code is attempting to use the height variable before it is declared and initialized.

myCanvas.height = height;
var height = 100

Just have to switch the order of those lines so that height has a valid value when you try to use it, like this:

var height = 100
myCanvas.height = height;

Link to working CodePen

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