In HTML5 Canvas, what's the simplest way to draw and move a line over an Image (already on the canvas), preserving the image underneath? (e.g. have a vertical line track the mouse X position)
My current canvas:
$(document).ready(function() {
canvas = document.getElementById("myCanvas");
context = canvas.getContext("2d");
imageObj = new Image();
imageObj.onload = function() {
context.drawImage(imageObj, 0,0);
}
imageObj.src = "http://example.com/some_image.png";
$('#myCanvas').click(doSomething);
});
P.S. I'm racing you against my Facebook network. May the best Lazyweb win (my gratitude) :)
You can get your "crosshairs" by listening to mousemove events and then:
Here is code and a Fiddle: http://jsfiddle.net/m1erickson/jEc7N/
or just use 2 layers:
You will have to do most of the ground-work with canvas which in this case you will have to implement the functionality to move the line and then redraw everything.
The steps can be:
You can redraw the background as a whole or you can optimize it to just draw over the last line.
Here is some example code of this and a live demo here:
Now all we need to do is to have a mechnism to update the background and the line for each move:
The custom line object is in this demo very simple:
If you are not gonna do anything specific with the image itself you can also set it as a background-image using CSS. You will still need to clear the canvas before redrawing the line though.
May this is not an actual answer, just in case you need it (in the future). Working with canvas would be better (and easier) with some library. I have tried EaselJS of CreateJS and find myself loving it. You can have a look at it EaselJS (I have done an example allow drawing and dragging image using EaselJS long time before)