2012-12-21 24 views
1

我想填補一下具體cell.Here網格小區的小區是我的代碼:如何填寫上單擊網格在畫布上的HTML5

function drawBox() 
    { 
     for (var row = 0; row < 14; row ++) 
     { 
      for (var column = 0; column < 13; column ++) 
      { 
       var x = column * 40; 
       var y = row * 40; 
       context.beginPath(); 
       context.rect(x, y, 40, 40); 
       context.fillStyle = "white"; 
       context.fill(); 
       context.lineWidth = 3; 
       context.strokeStyle = 'black'; 
       context.stroke(); 
      } 
     } 

    } 

回答

6

I've got a working sample here.Code

var canvas = document.getElementById("canvas"), 
 
    c = canvas.getContext("2d"), 
 
    boxSize = 40, 
 
    boxes = Math.floor(600/boxSize); 
 
canvas.addEventListener('click', handleClick); 
 
canvas.addEventListener('mousemove', handleClick); 
 

 
function drawBox() { 
 
    c.beginPath(); 
 
    c.fillStyle = "white"; 
 
    c.lineWidth = 3; 
 
    c.strokeStyle = 'black'; 
 
    for (var row = 0; row < boxes; row++) { 
 
    for (var column = 0; column < boxes; column++) { 
 
     var x = column * boxSize; 
 
     var y = row * boxSize; 
 
     c.rect(x, y, boxSize, boxSize); 
 
     c.fill(); 
 
     c.stroke(); 
 
    } 
 
    } 
 
    c.closePath(); 
 
} 
 

 
function handleClick(e) { 
 
    c.fillStyle = "black"; 
 

 
    c.fillRect(Math.floor(e.offsetX/boxSize) * boxSize, 
 
    Math.floor(e.offsetY/boxSize) * boxSize, 
 
    boxSize, boxSize); 
 
} 
 

 
drawBox();
<canvas id="canvas" width="600px" height="600px"></canvas>

我編輯drawBox()功能的位,以提高效率,也。

e.offsetX是鼠標座標,通過devide 40,然後Math.floor()此得到的細胞數,然後乘以40獲取單元的起點座標。

+0

非常感謝Cerbrus ...它幫助了! –

+0

謝謝你! <3。 –

+0

offsetX和offsetY應分別更改爲clientX和clientY。客戶端絕對適用於Firefox 37和Chromium,但抵消只適用於Chromium。 – Arcana