2017-07-07 43 views
0

下面的代碼應該在工具提示框中創建10x10個彩色框,它在灰色背景上在紅色和藍色之間交替。我希望每個畫布只有在畫布內時才響應鼠標。下面的代碼可以製作4個方形的灰色畫布,但是當鼠標放在最左邊的那個上面時,彩色框會出現在最右邊的畫布上。沒有其他的畫布工作。如何在JavaScript中製作多個點擊響應式畫布?

所以這裏是我的兩個問題。

  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*e.x-box, scale*e.y-box, box, box); 
 
    }, true); 
 
}; 
 
for (var key in the) workings(key); 
 
</script> 
 

 
</body> 
 
</html>

回答

1

這是因爲你沒有聲明變量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>

+0

完美!你的解釋很簡短明瞭。謝謝。 – jlettvin