簡體   English   中英

Javascript“ this”傳遞畫布以在頁面加載時起作用

[英]Javascript 'this' to pass a canvas to function on page load

我試圖將canvas HTML元素作為參數傳遞,我以為“這”可行,但我不太明白。 有人可以幫我使用'this'關鍵字在頁面加載時將畫布傳遞給main()嗎?

不起作用:

<html>
    <head>
    <title>Draw on Canvas</title>
    </head>
    <body onload=main(this.firstChild)><canvas></canvas></body>
    <script>
        function main(canv) {
            cntx = canv.getContext("2d");
            cntx.rect(10, 10, 100, 100);
            cntx.fill();
        }
    </script>
</html>

可以,但是想改用'this'關鍵字:

<html>
    <head>
    <title>Draw on Canvas</title>
    </head>
    <body onload=main(document.body.firstChild)><canvas></canvas></body>
    <script>
        function main(canv) {
            cntx = canv.getContext("2d");
            cntx.rect(10, 10, 100, 100);
            cntx.fill();
        }
    </script>
</html>

不起作用(未為canvas元素定義onload):

<html>
    <head>
    <title>Draw on Canvas</title>
    </head>
    <body><canvas onload=main(this)></canvas></body>
    <script>
        function main(canv) {
            cntx = canv.getContext("2d");
            cntx.rect(10, 10, 100, 100);
            cntx.fill();
        }
    </script>
</html>

可以使用'this',但是希望代碼無需單擊即可運行:

<html>
    <head>
    <title>Draw on Canvas</title>
    </head>
    <body><canvas onclick=main(this)></canvas></body>
    <script>
        function main(canv) {
            cntx = canv.getContext("2d");
            cntx.rect(10, 10, 100, 100);
            cntx.fill();
        }
    </script>
</html>

我建議您考慮使用另一種方法,因為如果將其混合到HTML標記中,可能會使整體腳本邏輯的表達復雜化。 更多的要貴點,但你不能在一個HTML標簽的onload背景下使用得到任何this超出了窗口,您可以創建定義在任何你想要的方式在window.onload后執行JS功能。

您已經在使用JavaScript定義畫布屬性,為什么不同時在JS中創建畫布呢!

您還可以看到如何擴展此功能,以打開在動態創建/附加更多畫布上的選項。

如果這對您不起作用,請告訴我這是否是一個抽象問題,我可能可以直接解決。

 <html> <head> <title>Draw on Canvas</title> </head> <body> <script> function createCanvasRect(x, y, width, height) { var canv = document.createElement('canvas'), cntx = canv.getContext('2d'); cntx.rect(x, y, width, height); cntx.fill(); return canv; } function load() { var canvas = createCanvasRect(10, 10, 100, 100); document.body.appendChild(canvas); } window.onload = load; </script> </body> </html> 

嘗試這個。 我從HTML中刪除了javascript,以獲得更簡潔的代碼。

 function main() { console.log(this); var cntx = this.getContext("2d"); cntx.rect(10, 10, 100, 100); cntx.fill(); } window.onload = function() { main.call(document.getElementById('main')); } 
 <html> <head> <title>Draw on Canvas</title> </head> <body> <canvas id="main"></canvas> </body> </html> 

您的問題是使用onload

通常,串聯連接的偵聽器被調用,就好像包裹在外部函數中一樣, 函數設置為調用偵聽器的元素。 但是, 附加到body元素上的 onload偵聽器不是這種情況。 它們的執行被延遲,並且在全局 / 窗口對象設置為this的情況下調用它們。

因此,您不能以這種方式使用它。

以下內容演示了將this作為全局對象調用body的負載偵聽器,但使用div元素this調用div的click偵聽器。

 <script> // Reference to global/window object var global = this; </script> <body onload="console.log(this === global)"> <div onclick="console.log(this.tagName)">clickable div</div> </body> 

有很多做事的方法。

用Javascript引用元素

要訪問DOM元素,您需要通過為其賦予唯一id對其進行id

<canvas id="myCanvas"></canvas>

注意id必須是唯一的,如果另一個元素具有相同的id,瀏覽器將進入怪癖模式(請參見下文)

然后,您可以使用其ID作為變量名稱直接訪問它。

 var ctx = myCanvas.getContext("2d");

有些人喜歡使用較慢和較痛苦的方法。

 var ctx = document.getElementById("myCanvas").getContext("2d");

或其他人使用

 var ctx = document.querySelector("#myCanvas").getContext("2d");

按順序獲取

所有這些方法都有一個問題。 當瀏覽器解析頁面時,它會從上到下一次將元素添加到DOM中。

如果在要使用的元素上方添加一些腳本,該腳本將找不到尚未創建的元素

<canvas id="topCan"></canvas>
<script> // this code is run when the browser finds it
    var ctx = topCan.getContext("2d"); // works as the element has been created
    var ctx1 = botCan.getContext("2d"); // no work as the element does not yet exist
</script>
<canvas id="botCan"></canvas>

因此,請確保將腳本添加到元素之后(並且在結束body標簽之前,請參見下面的怪癖模式)

有時,將腳本放在內容之后只是很不便。 那是當您將代碼放入在load事件中調用的函數中時。 只有將所有元素都添加到頁面后,該函數中的代碼才能運行。

如何收聽該事件取決於您自己,請參見下文

舉辦活動

直接分配事件處理程序被認為是錯誤的形式

 myCanvas.onclick = function(){};

甚至更糟

 <canvas onclick = "myFuction(this)"></canvas>

啟蒙之路充滿了那些說以下方式是

 const canvas = document.querySelector("#myCanvas");   
 canvas.addEventListener("click",myFunction);
 function myFunction(){ /* code */}

以上所有方法均有效,對與錯都不對,還有其他幾種方法。 哪種方法取決於您,我始終建議您使用最容易記住和使用的方法。

小心怪癖

但是有些事情你不應該做。 原因是某些布局使瀏覽器在2000年代末90年代初就想起了它,並且您沒有遵循規則(沒人真正知道的規則),以阻止它在同齡人旁邊顯得愚蠢,它將切換到怪癖模式。這不好,通常會使一切變慢。

可以觸發怪癖模式的一件事是將腳本標記放置在不應放置的位置。

因此,切勿將腳本標簽放在身體或頭部標簽之外

通往世界和平的道路總是將腳本標簽放到它們所屬的位置。

<html>
   <head>
      <script></script> <!-- browser is your friend -->
   </head>
   <body>
      <script></script> <!-- browser thinks your great -->
      <p> some content </p>
      <script></script> <!-- and you know everything-->
   </body>
</html>

黑暗之路。 如下放置腳本標簽

<script></script> <!-- wrong -->
<html>
   <script></script> <!-- wrong -->
   <head>

   </head>
   <script></script> <!-- oh so bad -->
   <body>
   </body>
   <script></script> <!-- oh so bad -->
</html>
<script></script> <!-- just playing with fire -->

單程

我該怎么辦取決於目前的潮流

<html>
    <head>
    <title>Draw on Canvas</title>
    </head>
    <body>
        <!-- id the canvas with a unique id -->
        <canvas id = myCanvas></canvas>
        <script>  // script after the element you are accessing
            const ctx = myCanvas.getContext("2d");
            ctx.rect(10, 10, 100, 100);
            ctx.fill();
         </script> <!-- ensure the script is inside the body tag -->
     </body>
</html>

暫無
暫無

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

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