|
| 1 | +<!DOCTYPE html> |
| 2 | +<meta charset="utf-8" /> |
| 3 | +<script src="paint.js"></script> |
| 4 | + |
| 5 | +<div></div> |
| 6 | +<script> |
| 7 | + var PixelEditor = class PixelEditor { |
| 8 | + constructor(state, config) { |
| 9 | + let { tools, controls, dispatch } = config; |
| 10 | + this.state = state; |
| 11 | + |
| 12 | + this.canvas = new PictureCanvas(state.picture, (pos) => { |
| 13 | + let tool = tools[this.state.tool]; |
| 14 | + let onMove = tool(pos, this.state, dispatch); |
| 15 | + if (onMove) { |
| 16 | + return (pos) => onMove(pos, this.state, dispatch); |
| 17 | + } |
| 18 | + }); |
| 19 | + this.controls = controls.map((Control) => new Control(state, config)); |
| 20 | + this.dom = elt( |
| 21 | + 'div', |
| 22 | + { |
| 23 | + tabIndex: 0, |
| 24 | + onkeydown: (event) => { |
| 25 | + if (event.key.toLowerCase() === 'z' && (event.ctrlKey || event.metaKey)) { |
| 26 | + event.preventDefault(); |
| 27 | + dispatch({ undo: true }); |
| 28 | + return; |
| 29 | + } |
| 30 | + const selectedTool = Object.keys(tools).find((name) => name.startsWith(event.key.toLowerCase())); |
| 31 | + if (selectedTool) { |
| 32 | + event.preventDefault(); |
| 33 | + dispatch({ tool: selectedTool }); |
| 34 | + } |
| 35 | + }, |
| 36 | + }, |
| 37 | + this.canvas.dom, |
| 38 | + elt('br'), |
| 39 | + ...this.controls.reduce((a, c) => a.concat(' ', c.dom), []) |
| 40 | + ); |
| 41 | + } |
| 42 | + syncState(state) { |
| 43 | + this.state = state; |
| 44 | + this.canvas.syncState(state.picture); |
| 45 | + for (let ctrl of this.controls) ctrl.syncState(state); |
| 46 | + } |
| 47 | + }; |
| 48 | + |
| 49 | + document.querySelector('div').appendChild(startPixelEditor({})); |
| 50 | +</script> |
0 commit comments