簡體   English   中英

Javascript Canvas-檢查是否單擊矩形

[英]Javascript Canvas - Check if clicking on rectangle

我有一個帶有網格的畫布,如果用戶單擊一個矩形,則應該用一種顏色填充它。 我遇到的麻煩是檢查用戶是否單擊了已經着色的矩形,因此程序可以刪除它或更改其顏色。

小提琴: http : //jsfiddle.net/JQd4j/2/

var build_canvas = document.getElementById("builder-canvas");
var build_context = build_canvas.getContext("2d");
var builder = function () {

    var x;
    for (x = 0.5; x <= 800; x += 15) {
        build_context.moveTo(x, 0);
        build_context.lineTo(x, 390);
    }

    var y;
    for (y = 0.5; y < 400; y += 10) {
        build_context.moveTo(0, y);
        build_context.lineTo(796, y);
    }

    build_context.strokeStyle = "#000000";
    build_context.stroke();
};
builder();

build_context.fillStyle = 'red';
build_canvas.onclick = function (e) {
    var rect = build_canvas.getBoundingClientRect(),
        x = e.clientX - rect.left,
        y = e.clientY - rect.top;

    x = Math.floor((x / 15)) * 15;
    y = Math.floor((y / 10)) * 10;

    build_context.fillRect(x + 1, y + 1, 14, 9);
}

先感謝您。

創建一個與網格相對應的數組。 單擊時,只需將數組的值設置為初始值即可。

用列數x行數初始化數組:

var cols = 27;
var rows = 40;
var clicked = new Uint8Array(cols * rows);  // initialized with 0

然后,只需計算該數組中單元格的索引並檢查一個值,例如1:

build_canvas.onclick = function (e) {

    var rect = build_canvas.getBoundingClientRect(),
        x = e.clientX - rect.left,
        y = e.clientY - rect.top,
        cellX = (x / 15)|0,           // get hor. cell position
        cellY = (y / 10)|0,           // get ver. cell position
        index = cols * cellY + cellX; // get array index

    if (clicked[index] === 1) {       // clicked ? (===1)
        alert('clicked already');     // do some action
        return;
    }

    clicked[index] = 1;               // is clicked now...

    x = cellX * 15;                   // get pixel position
    y = cellY * 10;

    build_context.fillRect(x + 1, y + 1, 14, 9);
}

改良的小提琴

代表2D數組的一維數組的索引始終是計算得到的width xy position + x position

另一種方法是,通過檢查要繪制的顏色來檢查顏色:

    var p = build_context.getImageData(x+1, y+1, 1, 1).data; 
    var hex = "#" + ("000000" + rgbToHex(p[0], p[1], p[2])).slice(-6);
    if(hex=='#000000'){
        build_context.fillRect(x + 1, y + 1, 14, 9);
    }else{
        //do something
    }


function rgbToHex(r, g, b) {
    if (r > 255 || g > 255 || b > 255)
        throw "Invalid color component";
    return ((r << 16) | (g << 8) | b).toString(16);
}

暫無
暫無

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

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