Reputation: 1167
I have already seen this question
What I want to achieve is practically the same, but using Jquery.
I have currently tried this, but I guess I can't use two nested click events.
$(function() {
var worksheetCanvas = $('#worksheet-canvas');
var context = worksheetCanvas.get(0).getContext("2d");
context.strokeStyle = "rgb(251, 243, 243)";
worksheetCanvas.click(function(e) {
context.beginPath();
var xCoordFirst = e.pageX;
var yCoordFirst = e.pageY;
context.moveTo(xCoordFirst, yCoordFirst);
worksheetCanvas.click(function(f) {
var xCoordSecond = f.pageX;
var yCoordSecond = f.pageY;
context.lineTo(xCoordSecond , yCoordSecond );
context.closePath();
context.stroke();
})
})
})
Also when I put some static values in lineTo()
, I get this, which recognizes the coordinates for the second point, thus drawing the line, even though it is useless if the user doesn't set by themselves the second point.
$(function() {
var worksheetCanvas = $('#worksheet-canvas');
var context = worksheetCanvas.get(0).getContext("2d");
context.strokeStyle = "rgb(251, 243, 243)";
worksheetCanvas.click(function(e) {
context.beginPath();
var xCoordFirst = e.pageX;
var yCoordFirst = e.pageY;
context.moveTo(xCoordFirst, yCoordFirst);
worksheetCanvas.click(function(f) {
var xCoordSecond = f.pageX;
var yCoordSecond = f.pageY;
context.lineTo(20 , 30);
context.closePath();
context.stroke();
})
})
})
Upvotes: 1
Views: 3371
Reputation: 305
var mouse = {
x: -1,
y: -1
};
$(document).ready(function(){
var cvs = $("canvas")[0].getContext("2d");
$("canvas").click(function(e){
if(mouse.x != -1 && mouse.y != -1){
cvs.beginPath();
cvs.moveTo(mouse.x, mouse.y);
cvs.lineTo(e.pageX, e.pageY);
cvs.closePath();
cvs.stroke();
mouse.x = -1;
mouse.y = -1;
}else{
mouse.x = e.pageX;
mouse.y = e.pageY;
}
});
});
Upvotes: 5