I am working on html 5 canvas and I am trying to take two points as input from users and then made a line pass through them. For it I need to attach two functions to event handler but it isn't working. Following is my codes for JavaScript and html 5.
Also is there any way to accomplish it?
Browser used: Google chrome
JavaScript Code:
var c = document.getElementById("myCanvas");
var graph = c.getContext("2d");
var posX = 100;
var posY = 50;
var finalX = posX;
var finalY = posY;
var array = [[]];
var i = 0;
c.width = window.innerWidth;
c.height = window.innerHeight;
graph.strokeRect(100,50,1000,500)
// for making graph
while(finalY < 550)
{
finalY +=10;
graph.beginPath();
graph.moveTo(posX , finalY);
graph.lineTo(posX + 1000, finalY);
if(finalY == 300) {
graph.lineWidth = 2;
graph.strokeStyle = "#000000";
} else {
graph.strokeStyle = "#000000";
graph.lineWidth = 1;
}
graph.stroke();
}
while(finalX <1100) {
finalX += 10;
graph.beginPath();
graph.moveTo(finalX, posY);
graph.lineTo(finalX, posY + 500);
if(finalX == 600) {
graph.lineWidth = 2;
graph.strokeStyle = "#000000";
} else {
graph.lineWidth = 1;
graph.strokeStyle = "#000000";
}
graph.stroke();
}
// for making rectangle wherever the user clicks
function rect(e) {
var ctx = c.getContext("2d");
var x = e.clientX;
var y = e.clientY;
var j = 0;
ctx.fillStyle = "rgb(255,0,0)";
ctx.fillRect(x,y,5,5);
array[i][j] = x;
array [i][j+1] = y;
}
var joinPts = function() {
graph.beginPath();
graph.moveTo(array[0][0],array[0][1]);
graph.lineTo(array[1][0],array[1][1]);
graph.strokeStyle = "#000000";
graph.lineWidth = 2;
graph.stroke();
}
function add() {
i+=1;
}
function combine() {
rect();
add();
}
function initialise() {
c.addEventListener("click", function (){combine();}, false);
// c.addEventListener("click", rect , false); This way also it isn't working
// c.addEventListener("click", add , false);
}
HTML Code:
<!DOCTYPE HTML>
<html>
<head>
<title>Canvas!!</title>
</head>
<body style="background:white" onload="initialise()">
<canvas id="myCanvas" style="background:#f6f6f6"></canvas>
<button name="Reset" type="reset" onclick="window.location.reload();">Reset</button>
<button name="Join" type="submit" onclick="joinPts">Join</button>
<footer>
<script src="main.js"></script>
</footer>
</body>
</html>
You need to actually call the
joinPts
function in youronclick
.Replace:
With:
Also, your
combined
function is lacking thee
event parameter: