SO - drawing lines on image

http://stackoverflow.com/q/8475142/1011582

by dzejkej

HTML

<img src="http://www.stlukeseye.com/images/img-amsler-grid.gif" id="img" />
<div>
    <button id="btn">Get image</button>
    x: <span id="x">?</span> y: <span id="y">?</span>
    <p>"Get image" button will work only if the image is hosted on the same domain as the script.</p>
</div>
<div id="output"></div>

JavaScript

$(function() {
 
  // retrieve the image
  var img = $("#img");
  
  // create a canvas element
  var canvas = document.createElement("canvas");
  
  // set dimensions to the width/height of img
  canvas.width = img.width();
  canvas.height = img.height();
  
  // replace img element with canvas
  img.replaceWith(canvas);
  
  // get context and draw image
  var ctx = canvas.getContext("2d");
  ctx.drawImage(img[0], 0, 0);
 
  var coordsArr = []; // [0] - coords of 1st click, [1] - coords of 2nd click
  $(canvas).click(function(e) {
    // get coordinates
    var coords = getCoordinates(canvas, e);
    
    // main logic here please :)
    // =========================
    
    // add coordinates to the array
    coordsArr.push(coords);
    // if there are 2 points (2 clicks)
    if (coordsArr.length === 2) {
      // draw the line
      draw(ctx, coordsArr);
      // reset the array
      coordsArr = [];
    }    
    // =========================
    
    // write the coordinates FYI
    $("span#x").text(coords.x);
    $("span#y").text(coords.y);
  });
  
  // if btn is clicked, create an <img/>, put data from canvas into it and append it to div
  $("#btn").click(function() {
    $("<img />").attr("src", canvas.toDataURL("image/png")).appendTo("#output");
  });
  
});

function draw(ctx, coordsArr) {
  // here you can put the logic that will calculate position of the grid intersections
  var newCoords = coordsArr; // currently nothing is done
  
  // draw the line with new coordinates
  drawLine(ctx, newCoords);
}

// get coordinates from the click event of the canvas
function getCoordinates(canvas, e) {
  var x;
  var y;
  
  if (e.pageX || e.pageY) { 
    x = e.pageX;
    y = e.pageY;
  } else { 
    x = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft; 
    y = e.clientY + document.body.scrollTop + document.documentElement.scrollTop; 
  } 
  x -= canvas.offsetLeft;
  y -= canvas.offsetTop;
  
  return { x : x, y: y };
}

// drawLine -...