微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

HTML5,JavaScript和在画布中绘制多个矩形

为什么我的多个矩形不会画在画布上?
<!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,25,"#333"))
    myRect.push(new Shape(0,40,39,80,100,"#333"))

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

      //console.log(x);

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

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

感谢帮助.

解决方法

好的,所以你几乎就在那里.
当您遍历矩形数组时,您将迭代数组键而不是对象本身(请参阅 How to Loop through plain JavaScript object with objects as members?).
另外,正如@ jimjimmy1995指出的那样,你需要使用.fillStyle设置填充.fillRect没有填充参数.

代码将起作用:

function Shape(x,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,"#333"));
    myRect.push(new Shape(0,"#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);

    }

}

原文地址:https://www.jb51.cc/html5/168788.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。