HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMajor

Drawing a grid on canvas

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
canvasdrawinggrid

Problem

I have created canvas (800x400) - and filled it with a grid. It works but the rendering of the grid (lines) takes around 3 seconds, which seems excessively long. Am I doing something wrong?



var drawGrid = function(w, h, id) {
var canvas = document.getElementById(id);
var ctx = canvas.getContext('2d');
ctx.canvas.width = w;
ctx.canvas.height = h;

for (x=0;x
`

Solution

Try using a SVG object on the canvas:


    
        
            
        
        
            
            
        
    

    


produces a grid like this:

whereas changing fill="url(#smallGrid)" to fill="url(#grid)" produces the following:

Which then you can feed into the canvas like the following:



var drawGrid = function(w, h, id) {
var canvas = document.getElementById(id);
var ctx = canvas.getContext('2d');
ctx.canvas.width = w;
ctx.canvas.height = h;

var data = ' \
\
\
\
\
\
\
\
\
\
\
';

var DOMURL = window.URL || window.webkitURL || window;

var img = new Image();
var svg = new Blob([data], {type: 'image/svg+xml;charset=utf-8'});
var url = DOMURL.createObjectURL(svg);

img.onload = function () {
ctx.drawImage(img, 0, 0);
DOMURL.revokeObjectURL(url);
}
img.src = url;
}
drawGrid(800, 400, "grid");

``



Of course, you'll need to play around with the sizes of the grid to match what you want. However you'll find that this method is much faster.

Code Snippets

<svg width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
    <defs>
        <pattern id="smallGrid" width="8" height="8" patternUnits="userSpaceOnUse">
            <path d="M 8 0 L 0 0 0 8" fill="none" stroke="gray" stroke-width="0.5" />
        </pattern>
        <pattern id="grid" width="80" height="80" patternUnits="userSpaceOnUse">
            <rect width="80" height="80" fill="url(#smallGrid)" />
            <path d="M 80 0 L 0 0 0 80" fill="none" stroke="gray" stroke-width="1" />
        </pattern>
    </defs>

    <rect width="100%" height="100%" fill="url(#smallGrid)" />
</svg>

Context

StackExchange Code Review Q#114702, answer score: 29

Revisions (0)

No revisions yet.