Javascript Canvas 网格(错误输出帮助!!)

标签 javascript canvas grid

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

            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 我希望它用矩形填充屏幕..请帮忙!:)

最佳答案

如果您只是想绘制一个盒子网格,我建议您这样做:

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);
}

关于Javascript Canvas 网格(错误输出帮助!!),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46381048/

相关文章:

javascript - 如果 ($ ('#selector' ).length == 0) 在 IE7 和 IE8 中不起作用

java - 在网格布局中垂直和水平缩放图像

css - 尝试创建网格/列短代码

Javascript - 为 onClick 事件调用函数

javascript - 我需要一些初级程序员的简单逻辑/编程练习

javascript - Animate CC HTML5 尝试通过调用字符串来更改全局变量

javascript - canvas.todataurl() 在 android 2.3.3 中不工作

javascript - Canvas Html5 Drawing App,移动 Canvas 导致大问题

jquery - 与 Flexigrid 保持一致的网格标题 ?

javascript - 如何使用 mailto 链接创建自定义联系表并在邮件中复制信息?