I want to draw a multiline (I mean some consecutive lines that share one coordinate with the previous and one with the next line) on mouse clicks. I have currently achieved this through mousemove event in jQuery:
var worksheetCanvas = $('#worksheet-canvas');
var context = worksheetCanvas.get(0).getContext("2d");
var mouse = {
x: -1,
y: -1
}
var parentOffset = $('#canvas-holder').parent().offset();
worksheetCanvas.click(function(e) {
mouse.x = e.pageX - parentOffset.left;
mouse.y = e.pageY - parentOffset.top;
context.beginPath();
context.moveTo(mouse.x, mouse.y);
$(this).mousemove(function(k) {
context.strokeStyle = "rgb(180,800,95)";
context.lineTo(k.pageX - parentOffset.left, k.pageY - parentOffset.top);
context.closePath();
context.stroke();
})
})
But as I can show you in this example, when I move my mouse cursor, it leaves a trail of lines, which somehow I need to delete to create the impression of one single movable line which needs another point to be defined. I have tried to clear the unneeded lines, but the 2d context only has an clearRect() method, whereas I’m looking for something like clearPath().
There is not
clearPathmethod according to the canvas referenceHowever, you are not going to need it anyways. If my assumptions are right, all you need to do is to store the values of previous strokes into an array:
I made a jsfiddle here so you can see it working and play around with it.
Clearing the canvas on every move is very effective and no performance issue.
Source Code with Explanations