![](/img/trans.png)
[英]How to create nxm HTML5 canvas Grid of objects (colored squares)?
[英]Count Amount of Colored Squares in Canvas
這是小提琴: http : //jsfiddle.net/sw31uokt/
這是我為統計canvas元素內的總點擊而設置的incrementValue函數的一些相關代碼。
我想做的是能夠顯示每種顏色的計數,因此“您已經放置了14個紅色像素,3個藍色像素,4個黑色像素”。
function incrementValue()
{
var value = parseInt(document.getElementById('number').value, 10);
value = isNaN(value) ? 0 : value;
value++;
document.getElementById('number').value = value;
}
$(c_canvas).click(function(evt) {
var pos = getNearestSquare(getMousePos(c_canvas, evt));
if (pos != null) {
context.fillStyle=(currentColor);
context.fillRect(pos.x,pos.y,19,19);
incrementValue();
}
});
基本上,MarkE上面所說的...
在外部范圍中,添加兩個新的變量:
var palette = ["333333", "0000ff", "a0522d", "46ad42", "808080", "ffc0cb", "d73952", "ffe2a8", "ffff7d", "ffffff"];//as originally defined in the .spectrum() call.
var gridModel = [];//Eventually a sparse array of sparse arrays, representing colored grid squares. Uncolored grid squares remain undefined.
和兩個新功能,在相同的范圍內:
function updateGridModel(pos, color) {
var x = (pos.x - 0.5) / 20;
var y = (pos.y - 0.5) / 20;
color = color.substr(1).toLowerCase();
if (!gridModel[x]) {
gridModel[x] = [];
}
gridModel[x][y] = palette.indexOf(color);
}
function paletteTally() {
//initialise an array, same length as palettes, with zeros
var arr = palette.map(function () {
return 0;
});
for (var x = 0; x < gridModel.length; x++) {
if (gridModel[x]) {
for (var y = 0; y < gridModel[x].length; y++) {
if (gridModel[x][y] !== undefined) {
arr[gridModel[x][y]] += 1;
}
}
}
}
return arr;
}
修改畫布的單擊處理程序以使gridModel保持最新:
$(c_canvas).click(function (evt) {
var pos = getNearestSquare(getMousePos(c_canvas, evt));
if (pos != null) {
context.fillStyle = currentColor;
context.fillRect(pos.x, pos.y, 19, 19);
incrementValue();
updateGridModel(pos, currentColor); //keep the gridModel up to date.
}
});
修改printColor()
如下:
function printColor(color) {
currentColor = color.toHexString();
$(".label").text(currentColor);
}
修改.spectrum()
選項,並添加對printColor()
的初始化調用,如下所示:
$("#showPaletteOnly").spectrum({
color: palette[0],
showPaletteOnly: true,
showPalette: true,
hideAfterPaletteSelect: true,
change: printColor,
palette: [palette] //<<<< palette is now defined as an outer var
});
printColor( $("#showPaletteOnly").spectrum('get') );//initialize currentcolor and $(".label").text(...) .
現在, paletteTally()
將返回一個與包含每種顏色計數的palette
一致的數組。
編輯1
上面的原始代碼未經測試,但現已調試,其中包括改進的spectrum
選項。 演示
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.