Load a single image to canvas
You have this canvas
<canvas id="myCanvas"></canvas>
Load an image by creating a new Image object and adding the image onto the canvas once the image has loaded.
The drawImage() method renders the image object onto the canvas.
<script type="text/javascript">
var context = $("#myCanvas")[0].getContext("2d");
var img = new Image();
img.src = "some-image.jpg";
img.onload = function() {
context.drawImage(img, 100, 100);
}
</script>
Get the position of the mouse in the window and send the coordinates to your processing page via AJAX:
<script type="text/javascript">
$(document).bind("click", function () {
// Add a click-handler to the image.
$("#myCanvas").bind("click", function (e) {
var $canvas = $(e.target);
var offset = $canvas.offset();
var xpos = e.clientX - offset.left;
var ypos = e.clientY - offset.top;
$.post("Process.aspx", { x: xpos, y: ypos } );
});
});
</script>
Load an array of images to canvas
Load an array of images and then call a function on each image when it's loaded.
The images will appear in a grid.
// array of images
var imgArray = [
"image01.jpg", "image02.jpg", "image03.jpg",
"image04.jpg", "image05.jpg", "image06.jpg",
"image07.jpg", "image08.jpg", "image09.jpg"
];
var preArray = []; // array of preload images
var count = 0; // count of loaded images
for (var i in imgArray) {
preArray[i] = new Image();
preArray[i].src = imgArray[i];
preArray[i].onload = function() {
count++;
// when the last image was loaded
if (count == imgArray.length) {
// draw preload array to the grid
imageLoaded(preArray);
}
}
}
function imageLoaded(img) {
// grid for canvas
var xpos = 100; // margin-left
var ypos = 100; // margin-top
var offset = 70; // offset for images
var cols = 3; // number of columns in a grid
//creates a grid
for(var i in img) {
var xoffset = xpos + offset * (i % cols);
var yoffset = ypos + offset * Math.floor(i / cols);
context.drawImage(img[i], xoffset, yoffset);
}
}