How do I draw a line with two mouse clicks on canvas?
The code is quite simple, but you have to get a good foundation:
Demo: http://jsfiddle.net/NpDdt/10/
JavaScript:
var clicks = 0;
var lastClick = [0, 0];
document.getElementById('canvas').addEventListener('click', drawLine, false);
function getCursorPosition(e) {
var x;
var y;
if (e.pageX != undefined && e.pageY != undefined) {
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;
}
return [x, y];
}
function drawLine(e) {
context = this.getContext('2d');
x = getCursorPosition(e)[0] - this.offsetLeft;
y = getCursorPosition(e)[1] - this.offsetTop;
if (clicks != 1) {
clicks++;
} else {
context.beginPath();
context.moveTo(lastClick[0], lastClick[1]);
context.lineTo(x, y, 6);
context.strokeStyle = '#000000';
context.stroke();
clicks = 0;
}
lastClick = [x, y];
};
Here is a complete example, based on the W3Schools example at http://www.w3schools.com/html5/tryit.asp?filename=tryhtml5_canvas_line
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="http://code.jquery.com/jquery-1.6.1.min.js"></script>
<script>
$(function(){
var point1 = new Array();
point1['x'] = false;
point1['y'] = false;
var point2 = new Array();
point2['x'] = false;
point2['y'] = false;
var c=document.getElementById("myCanvas");
var cxt=c.getContext("2d");
$(document).click(function(e){
if ( false === point1['x'] || false === point1['y']) {
point1['x'] = e.pageX;
point1['y'] = e.pageY;
return;
}
else if ( false === point2['x'] || false === point2['y'] ) {
point2['x'] = e.pageX;
point2['y'] = e.pageY;
console.log("second");
cxt.moveTo(point1['x'], point1['y']);
cxt.lineTo(point2['x'], point2['y']);
cxt.stroke();
}
});
});
</script>
</head>
<body>
<canvas id="myCanvas" width="200" height="200" style="border: 1px solid #000">Your browser does not support the canvas element.</canvas>
</body>
</html>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With