|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +import * as tiles from './tiles.js'; |
| 4 | +const tileNames = Object.keys( tiles ); |
| 5 | +let patternIndex = 0; |
| 6 | + |
| 7 | +const colors = [ |
| 8 | + [255,255,255], // White |
| 9 | + [255,0,0], [0,255,0], [0,0,255], // R G B |
| 10 | + [255,255,0], [255,0,255], [0,255,255], // C M Y |
| 11 | + [0,0,0] // Black |
| 12 | +]; |
| 13 | +let colorIndex = 0; |
| 14 | + |
| 15 | +function addOnLoad( f ){ |
| 16 | + var p = window.onload; |
| 17 | + window.onload = ()=>{ |
| 18 | + if( p ) p(); |
| 19 | + f(); |
| 20 | + } |
| 21 | +} |
| 22 | + |
| 23 | +function TileToImageData( tile, color ){ |
| 24 | + const rows = tile.length; |
| 25 | + const cols = tile[0].length; |
| 26 | + const buffer = new Uint8ClampedArray( rows * cols * 4 ); // 4 bytes per pixel (R,G,B,A) |
| 27 | + |
| 28 | + for( let y = 0; y < rows; y++ ){ |
| 29 | + const line = tile[y]; |
| 30 | + for( let x = 0; x < cols; x++ ){ |
| 31 | + const idx = ( y * cols + x ) * 4; |
| 32 | + [buffer[idx], buffer[idx + 1], buffer[idx + 2]] = line[x] !== ' ' ? [0, 0, 0] : color; |
| 33 | + buffer[idx + 3] = 255; |
| 34 | + } |
| 35 | + } |
| 36 | + return new ImageData( buffer, cols, rows ); |
| 37 | +} |
| 38 | + |
| 39 | +async function Update( name, canvas ){ |
| 40 | + let ctx = canvas.getContext( '2d' ); |
| 41 | + var dpr = window.devicePixelRatio || 1; |
| 42 | + |
| 43 | + const bitmap = await createImageBitmap( TileToImageData( tiles[name], colors[colorIndex] ) ); |
| 44 | + ctx.fillStyle = ctx.createPattern( bitmap, 'repeat' ); |
| 45 | + ctx.fillRect( 0, 0, canvas.offsetWidth * dpr, canvas.offsetHeight * dpr ); |
| 46 | +} |
| 47 | + |
| 48 | +addOnLoad( ()=>{ |
| 49 | + const canvas = document.getElementById( 'canvas' ); |
| 50 | + |
| 51 | + var dpr = window.devicePixelRatio || 1; |
| 52 | + canvas.width = canvas.offsetWidth * dpr; |
| 53 | + canvas.height = canvas.offsetHeight * dpr; |
| 54 | + |
| 55 | + Update( tileNames[patternIndex], canvas ); |
| 56 | + window.onresize = ()=> Update( tileNames[patternIndex], canvas ); |
| 57 | + |
| 58 | + canvas.onwheel = async ( event ) => { |
| 59 | + |
| 60 | + if( event.shiftKey ){ |
| 61 | + colorIndex = ( colorIndex + Math.sign( event.deltaY ) + colors.length ) % colors.length; |
| 62 | + } else { |
| 63 | + patternIndex = ( patternIndex + Math.sign( event.deltaY ) + tileNames.length ) % tileNames.length; |
| 64 | + } |
| 65 | + |
| 66 | + const canvas = document.getElementById( 'canvas' ); |
| 67 | + Update( tileNames[patternIndex], canvas ); |
| 68 | + event.preventDefault(); |
| 69 | + } |
| 70 | + |
| 71 | +}) |
0 commit comments