简单图形不会显示在画布中

时间:2019-10-24 16:38:33

标签: javascript html5-canvas

学习HTML5我遇到了一本有关图形和数据可视化的食谱。这是第一次练习,我无法显示图形。

我尝试了很多事情,甚至复制并粘贴了源代码以查看它是否有效,但没有成功:

这是代码: 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();   
        }
    }
}

我期望一个矩形块充满画布上显示的多种颜色的点。

1 个答案:

答案 0 :(得分:3)

这里的问题是代码在声明和初始化之前尝试使用height变量。

myCanvas.height = height;
var height = 100

只需切换这些行的顺序,以便在尝试使用height时具有有效值,就像这样:

var height = 100
myCanvas.height = height;

Link to working CodePen