简体   繁体   English

在画布内绘制预定义数量的点

[英]Drawing predefined number of dots inside a canvas

I am trying achieve the following: -Given two variables numberColumns/numberRows I want to draw a grid of rectangles or dots in a set width canvas for example 800x400 我正在尝试实现以下目标:-给出两个变量numberColumns / numberRows我想在设定宽度的画布(例如800x400)中绘制矩形或点的网格

I have tried several things, but I fail at getting the rectangles/dots the right size with the right spacing 我已经尝试了几件事,但是我无法使矩形/点具有正确的大小和正确的间距

This is an example I tried to draw one row. 这是我尝试绘制一行的示例。 I am trying to get to work on any given number of rows/columns 我试图在任何给定的行数/列数上工作

    function draw(){
            var width = 800;
            var height = 400;

            var nrow = 32;
            var ncol = 48;

            var canvas = document.getElementById('tutorial');
            if (canvas.getContext){
                var ctx = canvas.getContext('2d');
                //Have a border so drawing starts at 20,20
                var spacew = width - 40;
                var x = Math.floor(spacew/ncol);

                var currCol = 20;
                for(i = 1; i<ncol; i++){
                    ctx.beginPath();
                    ctx.arc(currCol, 20, x, 0, Math.PI*2, true);
                    ctx.closePath();
                    ctx.fill();

                    currCol = currCol + x*2;
                }

            }
        }

Any idea on how I would go about this, maybe an example? 关于我将如何解决这个问题的任何想法,也许是一个例子?

Thanks 谢谢

I have created an example here http://jsfiddle.net/J9MLq/7/ . 我在http://jsfiddle.net/J9MLq/7/创建了一个示例。 Each circle has a diameter that is a 2*radius . 每个圆的直径为2*radius i have put it when calculating the radius dynamically depending on the width of canvas in var x = width/ncol/2; 我已经根据var x = width/ncol/2;动态地确定画布的宽度来计算半径了var x = width/ncol/2; (You don't need any Math.floor/Math.ceil, otherwise you will have gaps between circles and also borders). (您不需要任何Math.floor / Math.ceil,否则圆和边框之间将有间隙)。 Also, now canvas element is resizable, your function accepts parameters draw(width, height) . 另外,现在canvas元素是可调整大小的,您的函数接受参数draw(width, height) Now you can play with the rows by yourself. 现在您可以自己玩行了。 You can extend the function to accept rows and columns amount as well. 您也可以扩展该函数以接受行和列的数量。 Just try it there... 只要在那里尝试...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM