簡體   English   中英

如何在JavaScript中制作多個點擊響應式畫布?

[英]How do I make multiple click responsive canvases in javascript?

下面的代碼應該在其內部畫布的工具提示上創建10x10彩色框,在灰色背景上的紅色和藍色之間交替。 我希望每個畫布僅在其在畫布內時才響應鼠標。 下面的代碼制作4個方形灰色畫布,但是當鼠標懸停在最左邊的畫布上時,最右邊的畫布中會出現彩色的框。 沒有其他畫布可以工作。

這是我的兩個問題。

  1. 為什么只有一個畫布處於活動狀態?
  2. 為什么框會出現在錯誤的畫布上?

 <!DOCTYPE html> <html> <body> <canvas id="c0" width="201" height="201"></canvas> <canvas id="c1" width="201" height="201"></canvas> <canvas id="c2" width="201" height="201"></canvas> <canvas id="c3" width="201" height="201"></canvas> <script> var colorno = ["#F77", "#077"]; var the = { 'c0': {}, 'c1': {}, 'c2': {}, 'c3': {} }; var box = 10; var workings = function(name) { instance = the[name]; instance.name = name; canvas = instance.canvas = document.getElementById(instance.name); instance.context = canvas.getContext("2d"); instance.index = 0; instance.context.fillStyle = "#777"; instance.context.fillRect(0, 0, canvas.width, canvas.height); scale = (canvas.width - box) / canvas.width; canvas.addEventListener("click", function(e) { instance.context.fillStyle = colorno[++instance.index&1]; instance.context.fillRect(scale*ex-box, scale*ey-box, box, box); }, true); }; for (var key in the) workings(key); </script> </body> </html> 

這是因為您沒有聲明變量instance ,從而導致在全局范圍內對其進行定義。 instance不斷被您的for循環覆蓋,因此在所有4個處理程序中, instance變量都指向同一對象。 在閉包中正確聲明變量非常重要。

var instance = value;      // declare function-scoped variable
let instance = value;      // declare block-scoped variable
function workings(args){}  // declare a function

這是已修復的代碼版本:

 <!DOCTYPE html> <html> <body> <canvas id="c0" width="201" height="201"></canvas> <canvas id="c1" width="201" height="201"></canvas> <canvas id="c2" width="201" height="201"></canvas> <canvas id="c3" width="201" height="201"></canvas> <script> var colorno = ["#F77", "#077"]; var the = { 'c0': {}, 'c1': {}, 'c2': {}, 'c3': {} }; var box = 10; // declare function function workings(name) { // declare variables var instance = the[name]; var canvas = instance.canvas = document.getElementById(name); // assign values instance.name = name; instance.context = canvas.getContext("2d"); instance.index = 0; instance.context.fillStyle = "#777"; instance.context.fillRect(0, 0, canvas.width, canvas.height); // attach click listener canvas.addEventListener("click", function(e) { instance.context.fillStyle = colorno[++instance.index&1]; instance.context.fillRect( // calculate correct coordinates e.pageX - canvas.offsetLeft - box / 2, e.pageY - canvas.offsetTop - box / 2, box, box); }, true); }; // invoke function for (var key in the) workings(key); </script> </body> </html> 

暫無
暫無

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

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