一千萬個為什麽

搜索

2D javascript表格圖形

挑戰

制作一個JavaScript程序,可以使用HTML表格作為畫布,讓每個單元格都有一個像素。 您可以在表單中或使用控制臺輸入位置和顏色值。

分數計算

  • +10 points for not using JQuery
  • +15 points for the cells scaling equally to keep the same table aspect ratio when the browser is scaled
  • +15 points for accomplishing the last thing without using any kind of CSS
  • +[number of upvotes]
  • +20 points if you do not label the cells' tags with coordinates (it counts if you make an JavaScript array like {"cell1-1": ..., "cell1-2": ..., "cell1-3": ...} but it doesn't count when you label the <td> tag itself, like <td id="cell-7-9"> or <td class="cell-8-1">)

So if you have 67 upvotes, no jQuery (+10), the cells scaling (+15) but by using CSS (no +15) and you do not label the cells (+20), then your score will be 67 + 10 + 15 + 0 + 20 = 112.

挑戰 ends on 20 Feb 2014, 4:00 PM GMT+0.

WINNERS:
Doorknob -> 61 + 3 = 64 points
Victor, with 60 + 1 = 61 points
they have very close scores so I couldn't exclude Victor.

最佳答案

得分:61

10(沒有jQuery)+ 15(縮放單元格)+15(縮放部分不使用CSS)+ 20(無標簽)+ 1(upvotes)

單擊單元格時,它將變為當前顏色。

JavaScript的

var w = h = 20, color = 'red'
function createTable() {
    var tbl = document.createElement('table')
    tbl.id = 'tbl'
    for (var i = 0; i < h; i++) {
        var tr = document.createElement('tr')
        for (var i2 = 0; i2 < w; i2++) {
            var td = document.createElement('td')
            td.addEventListener('mousedown', draw)
            tr.appendChild(td)
        }
        tbl.appendChild(tr)
    }
    document.body.appendChild(tbl)
    return tbl
}
function killTable(tbl) {
    tbl.parentNode.removeChild(tbl)
}
var tbl = createTable()

function draw(e) {
   e.preventDefault()
   this.style.backgroundColor = color
}

document.getElementById('finalize').addEventListener('click', finalize)
function finalize() {
    var tds = document.getElementsByTagName('td')
    for (var i = 0; i < tds.length; i++) {
        tds[i].style.border = 'none'
        tds[i].removeEventListener('mousedown', draw)
    }
    document.getElementById('optionsWrapper').style.display = 'none'
}

document.getElementById('changeColor').addEventListener('click', changeColor)
function changeColor() {
    color = document.getElementById('color').value
}

document.getElementById('changeDims').addEventListener('click', changeDims)
function changeDims() {
    var dims = document.getElementById('dims').value.split('x')
    w = +dims[0], h = +dims[1]

    killTable(tbl)
    tbl = createTable()
}

HTML

<div id='optionsWrapper'>
    <button id='finalize'>Finalize</button>
<input id='color' type='text' value='red' /><button id='changeColor'>Go</button>
<input id='dims' type='text' value='20x20' /><button id='changeDims'>Go</button> </div>

CSS

td {
    width: 5px;
    height: 5px;
    padding: 0;
    border: 1px solid black;
}

table {
    border-collapse: collapse;
}

的jsfiddle

http://的jsfiddle.net/D9u2N/1/

截圖

放大視圖(編輯時,點擊放大到完整尺寸):

screenshot

最終視圖(縮小):

screenshot 2

轉載註明原文: 2D javascript表格圖形