簡體   English   中英

將兩個函數附加到事件處理程序

[英]Attaching two functions to event handler

我正在html 5 canvas上工作,我試圖從用戶那里獲取兩點作為輸入,然后使一條線穿過它們。 為此,我需要將兩個函數附加到事件處理程序,但是它不起作用。 以下是我的JavaScript和html 5代碼。
還有什么辦法可以做到呢? 使用的瀏覽器:谷歌瀏覽器

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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM