HTML5 - Canvas, draw a grid - horizontal and vertical lines over an image.

Any idea how I can draw a grid with horizontal and vertical lines over an existing image in a canvas?
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Robert SchuttSoftware EngineerCommented:
based on code from one of your previous questions try something like this:
<div id="images"></div>
<canvas  style="margin:0;padding:0;position:relative;left:150px;top:50px;" id="imgCanvas" width="500" height="500"></canvas>
var canvas = document.getElementById("imgCanvas");
var context = canvas.getContext("2d");

var img = new Image();
img.src = '';
img.onload = function() {
    context.drawImage(this, 0, 0);

var scalex = 2, scaley = 2;
context.scale(scalex, scaley);   // Zoom 200 %

function drawGrid() {
    var x,
        xx = canvas.width / scalex,
        yy = canvas.height / scaley,
        nx = 9, // number of rows
        ny = 4; // number of columns
    for (x = 1; x < nx; x++) {
        y = xx * x / nx;
        context.moveTo(0, y);
        context.lineTo(xx, y);
    context.lineWidth = 5 / scalex;
    context.strokeStyle = "#d3d3d3";
    for (y = 1; y < ny; y++) {
        x = yy * y / ny;
        context.moveTo(x, 0);
        context.lineTo(x, yy);
    context.lineWidth = 5 / scaley;
    context.strokeStyle = "#d3d3d3";

function draw(e) {
    var pos = getMousePos(canvas, e);
    posx = pos.x;
    posy = pos.y;
    context.fillStyle = "#0000ff";
    context.fillRect(posx / scalex, posy / scaley, 4, 4);
window.addEventListener('mousemove', draw, false);

function getMousePos(canvas, evt) {
    var rect = canvas.getBoundingClientRect();
    return {
      x: evt.clientX - rect.left,
      y: evt.clientY -

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
JElsterAuthor Commented:
Awesome again!
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.