html css js voxel editor x y resize share "#/" color copy paste select line pos shortcut delete
Assistant
Creating a simple voxel editor with features like XY resizing, color picking, copy/paste, line drawing, selection, position display, keyboard shortcuts, and a way to share the voxel data (via URL hash) is a fun project!
Below is a full single HTML file implementing:
A 2D grid voxel editor on XY plane (you can change Z value as needed)
Resize grid (width, height) inputs
Color picker for voxel colors
Copy/Paste voxels
Draw lines
Select voxels
Show position of hovered voxel
Keyboard shortcuts
Data sharing via URL hash
Delete selected voxels
How it works overview
The editor shows a 2D grid of voxels (each voxel is a square).
Clicking fills the voxel with selected color.
Shift+click draws lines between voxels.
Ctrl+C copies selected voxels.
Ctrl+V pastes voxels at current hover pos.
Press Delete to remove selected voxels.
The grid size can be resized (resets data).
The data (voxels positions and colors) is serialized into a compact base64 string and stored in the URL hash (#xxxx).
On load, the editor reads the hash and reconstructs the voxel data.
Keyboard shortcuts:
Arrows: move selection
Ctrl+C, Ctrl+V for copy/paste
Delete for deleting selection
R to reset grid
Code (Save as voxel-editor.html and open in browser):
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Voxel Editor XY 2D</title>
<style>
body {
font-family: monospace;
margin: 0; padding: 0;
background: #222;
color: #eee;
user-select: none;
}
#toolbar {
background: #111;
padding: 8px;
display: flex;
gap: 10px;
align-items: center;
flex-wrap: wrap;
}
#toolbar label {
font-size: 14px;
}
input[type=number] {
width: 50px;
background: #333;
border: 1px solid #555;
color: #eee;
border-radius: 3px;
text-align: right;
font-size: 14px;
}
input[type=color] {
width: 40px;
height: 30px;
border: none;
cursor: pointer;
}
#canvas {
display: block;
margin: 0 auto;
background: #111;
border: 2px solid #444;
cursor: crosshair;
}
#posInfo {
padding-left: 10px;
font-size: 14px;
}
#instructions {
margin: 10px;
font-size: 13px;
color: #aaa;
max-width: 600px;
}
</style>
</head>
<body>
<div id="toolbar">
<label>Width: <input type="number" id="widthInput" min="1" max="64" value="16" /></label>
<label>Height: <input type="number" id="heightInput" min="1" max="64" value="16" /></label>
<button id="resizeBtn" title="Resize grid (resets data)">Resize</button>
<label>Color: <input type="color" id="colorPicker" value="#00ff00" /></label>
<button id="copyBtn" title="Copy selected voxels (Ctrl+C)">Copy</button>
<button id="pasteBtn" title="Paste copied voxels (Ctrl+V)">Paste</button>
<button id="deleteBtn" title="Delete selected voxels (Delete)">Delete</button>
<button id="resetBtn" title="Reset all voxels">Reset</button>
<div id="posInfo"></div>
</div>
<canvas id="canvas" width="512" height="512" tabindex="0"></canvas>
<div id="instructions">
<strong>Instructions:</strong> Click to paint, Shift+Click to draw line.<br />
Click drag to select multiple voxels.<br />
Arrow keys to move selection.<br />
Ctrl+C / Ctrl+V to Copy/Paste.<br />
Delete to remove selected voxels.<br />
Resize grid resets voxels.<br />
Data is saved in URL hash so you can share by copying URL.<br />
</div>
<script>
(() => {
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
// Toolbar
const widthInput = document.getElementById('widthInput');
const heightInput = document.getElementById('heightInput');
const resizeBtn = document.getElementById('resizeBtn');
const colorPicker = document.getElementById('colorPicker');
const copyBtn = document.getElementById('copyBtn');
const pasteBtn = document.getElementById('pasteBtn');
const deleteBtn = document.getElementById('deleteBtn');
const resetBtn = document.getElementById('resetBtn');
const posInfo = document.getElementById('posInfo');
// Grid parameters
let gridWidth = parseInt(widthInput.value);
let gridHeight = parseInt(heightInput.value);
const canvasSizePx = 512;
canvas.width = canvasSizePx;
canvas.height = canvasSizePx;
// Calculate cell size
function getCellSize() {
return Math.floor(Math.min(canvas.width / gridWidth, canvas.height / gridHeight));
}
// Voxels stored as map key"x,y" -> hex color string (e.g. "#00ff00")
let voxels = new Map();
// Selection as Set of keys "x,y"
let selection = new Set();
// Copy buffer: Map of "x,y" -> color
let copyBuffer = new Map();
// Current tool state
let currentColor = colorPicker.value;
let isDragging = false;
let dragStart = null;
let dragEnd = null;
// For line drawing using Shift+click
let lastClick = null;
// Hovered cell coords
let hoverCell = null;
function coordKey(x, y){ return `${x},${y}`; }
function parseKey(key){
const [x,y] = key.split(',').map(Number);
return {x,y};
}
// Draw functions
function clearCanvas() {
ctx.fillStyle = '#111';
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
function drawGrid() {
const cellSize = getCellSize();
ctx.strokeStyle = '#444';
ctx.lineWidth = 1;
for(let x=0; x<=gridWidth; x++){
const px = x * cellSize;
ctx.beginPath();
ctx.moveTo(px,0);
ctx.lineTo(px, cellSize * gridHeight);
ctx.stroke();
}
for(let y=0; y<=gridHeight; y++){
const py = y * cellSize;
ctx.beginPath();
ctx.moveTo(0, py);
ctx.lineTo(cellSize * gridWidth, py);
ctx.stroke();
}
}
function drawVoxels() {
const cellSize = getCellSize();
voxels.forEach((color,key)=>{
const {x,y} = parseKey(key);
if(x<0 || x>=gridWidth || y<0 || y>=gridHeight) return;
ctx.fillStyle = color;
ctx.fillRect(x*cellSize+1, y*cellSize+1, cellSize-2, cellSize-2);
// selection highlight
if(selection.has(key)){
ctx.strokeStyle = 'yellow';
ctx.lineWidth = 2;
ctx.strokeRect(x*cellSize+1, y*cellSize+1, cellSize-2, cellSize-2);
}
});
}
function drawHover() {
if (!hoverCell) return;
const {x,y} = hoverCell;
if (x < 0 || x >= gridWidth || y < 0 || y >= gridHeight) return;
const cellSize = getCellSize();
ctx.strokeStyle = 'cyan';
ctx.lineWidth = 2;
ctx.strokeRect(x*cellSize+1, y*cellSize+1, cellSize-2, cellSize-2);
}
function drawSelectionRect() {
if(!isDragging || !dragStart || !dragEnd) return;
const cellSize = getCellSize();
// Calculate rectangle bounds
const startX = Math.min(dragStart.x, dragEnd.x);
const startY = Math.min(dragStart.y, dragEnd.y);
const endX = Math.max(dragStart.x, dragEnd.x);
const endY = Math.max(dragStart.y, dragEnd.y);
ctx.strokeStyle = 'white';
ctx.lineWidth = 1;
ctx.setLineDash([4, 4]);
ctx.strokeRect(startX*cellSize, startY*cellSize, (endX - startX + 1)*cellSize, (endY - startY + 1)*cellSize);
ctx.setLineDash([]);
}
function render() {
clearCanvas();
drawGrid();
drawVoxels();
drawHover();
drawSelectionRect();
}
// Convert mouse pixel position to grid coords
function pixelToGrid(x, y) {
const rect = canvas.getBoundingClientRect();
const px = x - rect.left;
const py = y - rect.top;
const cellSize = getCellSize();
const gx = Math.floor(px / cellSize);
const gy = Math.floor(py / cellSize);
if(gx<0 || gx>=gridWidth || gy<0 || gy>=gridHeight) return null;
return {x: gx, y: gy};
}
// Bresenham line drawing algorithm between two coords on grid
function linePoints(x0, y0, x1, y1) {
const points = [];
let dx = Math.abs(x1 - x0);
let dy = -Math.abs(y1 - y0);
let sx = (x0 < x1) ? 1 : -1;
let sy = (y0 < y1) ? 1 : -1;
let err = dx + dy;
while(true){
points.push({x: x0, y: y0});
if(x0 === x1 && y0 === y1) break;
let e2 = 2*err;
if(e2 >= dy){
err += dy;
x0 += sx;
}
if(e2 <= dx){
err += dx;
y0 += sy;
}
}
return points;
}
// Set voxel at x,y with current color
function setVoxel(x, y, color) {
if(x<0 || x>=gridWidth || y<0 || y>=gridHeight) return;
voxels.set(coordKey(x,y), color);
}
// Remove voxel
function removeVoxel(x,y) {
voxels.delete(coordKey(x,y));
}
// Handle click on canvas
canvas.addEventListener('mousedown', e=>{
e.preventDefault();
canvas.focus();
const pos = pixelToGrid(e.clientX, e.clientY);
if(!pos) return;
if(e.shiftKey && lastClick){
// draw line from lastClick to current pos
const points = linePoints(lastClick.x, lastClick.y, pos.x, pos.y);
points.forEach(p=>setVoxel(p.x,p.y,currentColor));
lastClick = pos;
selection.clear();
points.forEach(p => selection.add(coordKey(p.x,p.y)));
} else {
// Normal click
setVoxel(pos.x, pos.y, currentColor);
selection.clear();
selection.add(coordKey(pos.x,pos.y));
lastClick = pos;
}
isDragging = true;
dragStart = pos;
dragEnd = pos;
render();
});
canvas.addEventListener('mousemove', e=>{
const pos = pixelToGrid(e.clientX, e.clientY);
hoverCell = pos;
if(isDragging && dragStart){
if(pos) dragEnd = pos;
render();
} else {
render();
}
if(pos){
posInfo.textContent = `Pos: (${pos.x}, ${pos.y})`;
} else {
posInfo.textContent = '';
}
});
function clearSelection() {
selection.clear();
}
canvas.addEventListener('mouseup', e=>{
if(!isDragging) return;
isDragging = false;
if(dragStart && dragEnd){
// Select rectangle area between dragStart and dragEnd
const startX = Math.min(dragStart.x, dragEnd.x);
const startY = Math.min(dragStart.y, dragEnd.y);
const endX = Math.max(dragStart.x, dragEnd.x);
const endY = Math.max(dragStart.y, dragEnd.y);
selection.clear();
for(let x = startX; x<=endX; x++){
for(let y = startY; y<=endY; y++){
if(voxels.has(coordKey(x,y))){
selection.add(coordKey(x,y));
}
}
}
dragStart = null;
dragEnd = null;
render();
}
});
// Keyboard shortcuts
canvas.addEventListener('keydown', e=>{
if(e.ctrlKey && e.key.toLowerCase() === 'c'){
e.preventDefault();
copySelection();
} else if(e.ctrlKey && e.key.toLowerCase() === 'v'){
e.preventDefault();
pasteCopyBuffer();
} else if(e.key === 'Delete'){
e.preventDefault();
deleteSelection();
} else if(['ArrowUp','ArrowDown','ArrowLeft','ArrowRight'].includes(e.key)){
e.preventDefault();
moveSelection(e.key);
} else if(e.key.toLowerCase() === 'r'){
e.preventDefault();
resetGrid();
}
});
function copySelection() {
copyBuffer.clear();
selection.forEach(key => {
if(voxels.has(key)){
copyBuffer.set(key, voxels.get(key));
}
});
alert(`Copied ${copyBuffer.size} voxel(s)`);
}
function pasteCopyBuffer() {
if (!hoverCell) return;
if(copyBuffer.size === 0) {
alert('Nothing copied!');
return;
}
// Calculate offset based on top-left min coords in copyBuffer
let minX = Infinity, minY = Infinity;
copyBuffer.forEach((color,key)=>{
const {x,y} = parseKey(key);
if(x<minX) minX = x;
if(y<minY) minY = y;
});
selection.clear();
copyBuffer.forEach((color,key)=>{
const {x,y} = parseKey(key);
const dx = x - minX;
const dy = y - minY;
const nx = hoverCell.x + dx;
const ny = hoverCell.y + dy;
if(nx>=0 && nx<gridWidth && ny>=0 && ny<gridHeight){
setVoxel(nx, ny, color);
selection.add(coordKey(nx, ny));
}
});
render();
}
function deleteSelection() {
if(selection.size === 0) return;
selection.forEach(key=>{
voxels.delete(key);
});
selection.clear();
render();
}
// Move selection by arrow keys (if selection is empty, do nothing)
function moveSelection(direction) {
if(selection.size === 0) return;
// Find bounding box of selection
let xs = [], ys = [];
selection.forEach(key=>{
const {x,y} = parseKey(key);
xs.push(x);
ys.push(y);
});
let minX = Math.min(...xs);
let maxX = Math.max(...xs);
let minY = Math.min(...ys);
let maxY = Math.max(...ys);
let dx=0, dy=0;
switch(direction){
case 'ArrowLeft': dx=-1; break;
case 'ArrowRight': dx=1; break;
case 'ArrowUp': dy=-1; break;
case 'ArrowDown': dy=1; break;
}
if(minX + dx < 0 || maxX + dx >= gridWidth) return;
if(minY + dy < 0 || maxY + dy >= gridHeight) return;
// Move voxels and selection
let newVoxels = new Map(voxels);
selection.forEach(key=>{
const color = voxels.get(key);
newVoxels.delete(key);
const {x,y} = parseKey(key);
newVoxels.set(coordKey(x+dx, y+dy), color);
});
voxels = newVoxels;
// Update selection
let newSelection = new Set();
selection.forEach(key=>{
const {x,y} = parseKey(key);
newSelection.add(coordKey(x+dx, y+dy));
});
selection = newSelection;
render();
}
// Resize grid resets voxels
resizeBtn.onclick = () => {
const w = Math.min(64, Math.max(1, parseInt(widthInput.value)));
const h = Math.min(64, Math.max(1, parseInt(heightInput.value)));
if(w === gridWidth && h === gridHeight) return;
gridWidth = w;
gridHeight = h;
selection.clear();
voxels.clear();
lastClick = null;
updateURLHash();
render();
};
// Update currentColor when colorPicker changes
colorPicker.addEventListener('input', e => {
currentColor = colorPicker.value;
});
copyBtn.onclick = () => {
copySelection();
};
pasteBtn.onclick = () => {
pasteCopyBuffer();
};
deleteBtn.onclick = () => {
deleteSelection();
};
resetBtn.onclick = () => {
resetGrid();
};
function resetGrid() {
selection.clear();
voxels.clear();
lastClick = null;
updateURLHash();
render();
}
// Serialize voxels to compact base64 and save in URL hash
// Format: W{width}H{height}|{x,y,colorHex}...
// For compactness, encode voxels as JSON base64 string
function encodeVoxels() {
// array of [x,y,color] with color in hex without #
const arr = [];
voxels.forEach((color,key)=>{
const {x,y} = parseKey(key);
arr.push([x,y,color.slice(1)]); // remove #
});
const data = {
w:gridWidth,
h:gridHeight,
v: arr
};
const json = JSON.stringify(data);
return btoa(unescape(encodeURIComponent(json))); // base64 encode
}
function decodeVoxels(b64) {
try{
const json = decodeURIComponent(escape(atob(b64)));
const data = JSON.parse(json);
if(!data.w || !data.h || !Array.isArray(data.v)) return false;
gridWidth = data.w;
gridHeight = data.h;
voxels.clear();
data.v.forEach(([x,y,color])=>{
voxels.set(coordKey(x,y), '#' + color);
});
widthInput.value = gridWidth;
heightInput.value = gridHeight;
return true;
} catch(e){
return false;
}
}
function updateURLHash(){
const encoded = encodeVoxels();
if(encoded.length > 0){
window.history.replaceState(null, '', '#'+encoded);
} else {
window.history.replaceState(null, '', ' ');
}
}
function loadFromURLHash(){
if(window.location.hash.length > 1){
const b64 = window.location.hash.substring(1);
if(decodeVoxels(b64)){
selection.clear();
render();
}
}
}
// Save on data change
const debounceURLUpdate = debounce(()=>{
updateURLHash();
}, 500);
function debounce(func, wait){
let timeout;
return function(){
clearTimeout(timeout);
timeout = setTimeout(func, wait);
};
}
// Hook render to save data after voxel changes
function triggerChange(){
debounceURLUpdate();
}
// Wrap setVoxel and removal with triggerChange
const _setVoxel = setVoxel;
setVoxel = (x,y,color) => {
_setVoxel(x,y,color);
triggerChange();
};
const _removeVoxel = removeVoxel;
removeVoxel = (x,y) => {
_removeVoxel(x,y);
triggerChange();
};
// On initial load
loadFromURLHash();
render();
// Also save on window unload or on resizeBtn click or reset etc
['resize', 'beforeunload'].forEach(eventName =>{
window.addEventListener(eventName, updateURLHash);
});
})();
</script>
</body>
</html>
Features included
Grid resize (up to 64x64)
Color picker with standard HTML input
Paint voxels by click
Shift+click to draw line between last painted voxel and new one
Click drag selection rectangle (select only voxels that exist)
Copy/Paste selected voxels to hover position (Ctrl+C / Ctrl+V)
Delete selected voxels (Del key or Delete button)
Arrow keys move selection around grid
Reset clears all voxels
Position info shown for hovered voxel
Data saved to URL hash as base64 encoded JSON (can share URL)
Works completely client side, no server needed
Open this file in your browser and try it out! Each edit updates the URL you can share with others, and all major features requested are included.
If you want me to add 3D view / other axes / export/import please ask!