const drawNes = bytes => { let canvas = e("#id-canvas") let context = canvas.getContext('2d') let tileNum = 8//一页8x8个tiles let tileSize = 8//一个tile有8x8个像素 let pixelwidth = 10//每个像素的宽度 let numberOfBytesPerTile = 16//16个字节一个图块 for (let i = 0; i < tileNum; i++) { for (let j = 0; j < tileNum; j++) { //算出bytes let x = j * tileSize * pixelwidth let y = i * tileSize * pixelwidth let index = window.offset + (i * tileNum + j) * numberOfBytesPerTile //其实应该drawTile更准确 drawTile(context, bytes.slice(index), x, y, pixelwidth) } } }
const drawTile = (context, data, x, y, pixelwidth) =>{ const colors = [ 'white', '#fe1000', '#ffb010', '#aa3030', ] let w = pixelwidth let h = pixelwidth for (let i = 0; i < 8; i++) { let p1 = data[i] let p2 = data[i + 8] for (let j = 0; j < 8; j++) { //8 bit per line //在j循环中每一次画一个像素点 //78 69 //0100 1110 0100 0101 let c1 = (p1 >> (7 - j)) & 0b00000001 let c2 = (p2 >> (7 - j)) & 0b00000001 let pixel = (c2 << 1) + c1 // if (pixel == 0){ // continue // } let color = colors[pixel] context.fillStyle = color let px = x + j * w let py = y + i * h context.fillRect(px, py, w, h) } } }