我正在html 5画布上工作,我试图采取两点作为用户的输入,然后使一行通过它们。对于它,我需要将两个函数附加到事件处理程序,但它不工作。以下是我的JavaScript和html 5代码。
还有什么方法可以实现吗?使用浏览器:Google chrome
JavaScript代码:
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代码:
<!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>
您需要在onclick
中实际调用joinPts
函数。
替换:
onclick="joinPts"
:
onclick="joinPts()"
同样,您的combined
函数缺少e
事件参数:
function combine(e) { // Accept a `e` parameter,
rect(e); // and pass it to `rect`.
add();
}
function initialise() {
c.addEventListener("click", combine, false); // No need to wrap `combine` in a function
}