我正在研究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>
答案 0 :(得分:0)
您需要实际调用joinPts
中的onclick
功能。
替换:
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
}