簡體   English   中英

在html5中單擊畫布上的網格時如何填充單元格

[英]how to fill a cell on clicking the grid on canvas in 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();
            }
        }

    }

我這里有一個工作樣本。 代碼

 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是鼠標坐標,除以40 ,然后使用Math.floor()來獲取單元格編號,然后乘以40以獲取該單元格的起始坐標。

暫無
暫無

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

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