首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Javascript画布网格(错误的输出帮助!!)

Javascript画布网格(错误的输出帮助!!)
EN

Stack Overflow用户
提问于 2017-09-23 23:11:45
回答 1查看 71关注 0票数 0

嗨,我正在尝试用javascript/canvas创建一个网格,但是我有一些问题,这里是我的代码: var canvas = document.getElementById("canvas");var ctx = canvas.getContext("2d");

代码语言:javascript
复制
            var width = 600;
            var height = 700;

            canvas.width=width;
            canvas.height=height;

            function Cell(x,y,width,height){
                this.x=x;
                this.y=y;
                this.width=width;
                this.height=height;
                this.draw=function(){
                    ctx.rect(this.x,this.y,this.width,this.height);
                    ctx.stroke();
                }
            }

            var x = 0;
            var y = 0;
            var width = 20;
            var height = 20;

            var cell = new Cell(x,y,width,height);

            var rows = 35;
            var cols = 30;

            function drawGrid(){
                for(var i=0; i<rows; i++){
                    for(var j=0; j<cols; j++){
                        cell.y+=cell.height;
                        cell.x+=cell.width;
                        cell.draw();
                    }
                }


            }

            setInterval(drawGrid,1);

这是输出:The grid so far我希望它用矩形填充屏幕。请帮帮忙!:)

EN

回答 1

Stack Overflow用户

发布于 2018-06-25 01:41:37

如果你只是想画一个方框的网格,我建议这样做:

代码语言:javascript
复制
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");

//change these if you dont want to fill the whole canvas
var h = c.height; //height of grid 
var w = c.width;  //width of grid

var div=20; //box size

for(i=0; i<h/div+1; i++){
  //Horizontal Line
  ctx.moveTo(0,i*div);
  ctx.lineTo(h,i*div); 
  //Vertial Line
  ctx.moveTo(i*div,0);
  ctx.lineTo(i*div,w);
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46381048

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档