【问题标题】:HTML5, JavaScript and drawing multiple rectangles in a canvasHTML5、JavaScript 和在画布中绘制多个矩形
【发布时间】:2025-12-31 12:20:13
【问题描述】:

为什么我的多个矩形不能在画布中绘制?

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title></title>
    <script src="Scripts/jquery-1.9.1.min.js"></script>
  </head>
  <body>
    <canvas id="myCanvas" width="500" height="500" style="border:1px solid red">
      <p>Your browser doesn't support canvas.</p>
    </canvas>
  </body>
</html>

<script type ="text/javascript">  
  function Shape(x, y, w, h, fill) {
    this.x = x;
    this.y = y;
    this.w = w;
    this.h = h;
    this.fill = fill;
  }

  // get canvas element.
  var elem = document.getElementById('myCanvas');

  // check if context exist
  if (elem.getContext) {

    var myRect = [];

    myRect.push(new Shape(10, 0, 25, 25, "#333"))
    myRect.push(new Shape(0, 40, 39, 25, "#333"))
    myRect.push(new Shape(0, 80, 100, 25, "#333"))

    context = elem.getContext('2d');
    for (i in myRect) {

      //console.log(x);

      context.fillRect(i.x, i.y, i.w, i.h)
    }
    //// x, y, width, height
    //context.fillRect(0, 0, 50, 50);

    //// x, y, width, height      
    //context.fillRect(75, 0, 50, 50);
  }
</script>  

感谢您的帮助。

【问题讨论】:

  • 我稍后会看一下您的代码,但只是想让您知道 jQuery 的 jCanvas 插件大大简化了画布上的绘图。你可能想看看它。 :)

标签: javascript html canvas html5-canvas


【解决方案1】:

好的,你就快到了。 当您遍历矩形数组时,您遍历的是数组 key 而不是对象本身(请参阅How to Loop through plain JavaScript object with objects as members?)。 另外,正如@jimjimmy1995 指出的那样,您需要使用.fillStyle 设置填充,因为.fillRect 没有填充参数。

此代码将起作用:

function Shape(x, y, w, h, fill) {
    this.x = x;
    this.y = y;
    this.w = w;
    this.h = h;
    this.fill = fill;
}

// get canvas element.
var elem = document.getElementById('myCanvas');

// check if context exist
if (elem.getContext) {

    var myRect = [];

    myRect.push(new Shape(10, 0, 25, 25, "#333"));
    myRect.push(new Shape(0, 40, 39, 25, "#333"));
    myRect.push(new Shape(0, 80, 100, 25, "#333"));

    context = elem.getContext('2d');
    for (var i in myRect) {
        oRec = myRect[i];
        context.fillStyle = oRec.fill;
        context.fillRect(oRec.x, oRec.y, oRec.w, oRec.h);

    }

}

【讨论】:

    【解决方案2】:

    你不需要给它填充颜色吗?

    context.fillStyle = i.fill;
    context.fillRect(i.x,i.y,i.w,i.h);
    

    【讨论】:

    • 是的,你是对的 - 但这不是主要问题 - 在循环中获取数组值存在问题。
    • 您似乎缺少一些行终止符。你有任何错误吗?
    • 呵呵没问题;它达到了一个地步,你开始用分号结束句子,而不仅仅是代码; :P
    最近更新 更多