html css js voxel editor x y resize share "#/" color copy paste select line pos shortcut
Assistant
You're looking for a voxel editor implemented with HTML, CSS, and JavaScript that supports features like manipulating voxels in an XY grid, resizing, sharing via URL (hash), color selection, copy-paste, selecting voxels or lines, position display, and keyboard shortcuts. Below is a minimal but functional example that incorporates these features.
Features implemented:
Voxel grid with adjustable width and height
Pixel (voxel) coloring
XY resizing
Color picker
Copy/paste selected voxels
Select/deselect voxels (including line selection with Shift key)
Display voxel position on hover or selection
Share editor state via URL hash encoding
Keyboard shortcuts for common actions
Here's the full code:
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Voxel Editor</title>
<style>
body {
font-family: sans-serif;
margin: 0;
padding: 0;
user-select: none;
background: #222;
color: #eee;
display: flex;
flex-direction: column;
height: 100vh;
}
#toolbar {
background: #333;
padding: 10px;
display: flex;
gap: 1em;
align-items: center;
}
#toolbar input[type=number] {
width: 4em;
}
#toolbar > * {
background: #444;
border: none;
color: #eee;
font-size: 1em;
padding: 0.25em 0.5em;
border-radius: 3px;
}
#toolbar > label {
font-weight: bold;
}
#canvas-container {
flex: 1;
background: #111;
display: flex;
justify-content: center;
align-items: center;
overflow: auto;
}
canvas {
image-rendering: pixelated;
background: #000;
cursor: crosshair;
border: 1px solid #555;
}
#pos-display {
margin-left: auto;
font-size: 0.9em;
font-weight: bold;
}
</style>
</head>
<body>
<div id="toolbar">
<label>Width: <input type="number" id="width" min="1" max="64" value="16" /></label>
<label>Height: <input type="number" id="height" min="1" max="64" value="16" /></label>
<label>Color: <input type="color" id="color" value="#ff0000" /></label>
<button id="resize-btn" title="Resize grid (ENTER also resizes)">Resize</button>
<button id="copy-btn" title="Copy selected voxels (Ctrl+C)">Copy</button>
<button id="paste-btn" title="Paste at selected voxel or offset (Ctrl+V)">Paste</button>
<button id="clear-btn" title="Clear all voxels">Clear</button>
<button id="share-btn" title="Copy share link">Share URL</button>
<div id="pos-display">Pos: -</div>
</div>
<div id="canvas-container">
<canvas id="canvas" width="512" height="512"></canvas>
</div>
<script>
(() => {
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
const widthInput = document.getElementById("width");
const heightInput = document.getElementById("height");
const colorInput = document.getElementById("color");
const resizeBtn = document.getElementById("resize-btn");
const copyBtn = document.getElementById("copy-btn");
const pasteBtn = document.getElementById("paste-btn");
const clearBtn = document.getElementById("clear-btn");
const shareBtn = document.getElementById("share-btn");
const posDisplay = document.getElementById("pos-display");
// Configuration
let gridWidth = parseInt(widthInput.value);
let gridHeight = parseInt(heightInput.value);
let voxelSize = 32; // Pixels per voxel on canvas (for zoom)
// Data structure: 2D array of colors (hex strings or null)
let grid = [];
// Selection set: store selected voxels as strings "x,y"
let selection = new Set();
let clipboard = null; // copy buffer
let dragSelecting = false;
let dragStart = null;
let lastHovered = null;
// Initialize grid empty
function resetGrid(w, h) {
grid = [];
selection.clear();
for(let y=0; y<h; y++) {
const row = [];
for(let x=0; x<w; x++) {
row.push(null);
}
grid.push(row);
}
}
function drawGrid() {
const cw = canvas.width;
const ch = canvas.height;
ctx.clearRect(0, 0, cw, ch);
// Draw colored voxels
for(let y=0; y<gridHeight; y++) {
for(let x=0; x<gridWidth; x++) {
const color = grid[y][x];
if(color){
ctx.fillStyle = color;
ctx.fillRect(x*voxelSize, y*voxelSize, voxelSize, voxelSize);
}
}
}
// Draw selection
ctx.strokeStyle = '#0ff';
ctx.lineWidth = 2;
for(const pos of selection){
const [x, y] = pos.split(",").map(Number);
ctx.strokeRect(x*voxelSize+1, y*voxelSize+1, voxelSize-2, voxelSize-2);
}
// Draw grid lines
ctx.strokeStyle = '#444';
ctx.lineWidth = 1;
for(let x=0; x<=gridWidth; x++){
ctx.beginPath();
ctx.moveTo(x*voxelSize,0);
ctx.lineTo(x*voxelSize, gridHeight*voxelSize);
ctx.stroke();
}
for(let y=0; y<=gridHeight; y++){
ctx.beginPath();
ctx.moveTo(0,y*voxelSize);
ctx.lineTo(gridWidth*voxelSize,y*voxelSize);
ctx.stroke();
}
}
// Convert mouse pixel to voxel coordinates
function pixelToVoxel(px, py){
const rect = canvas.getBoundingClientRect();
const x = Math.floor((px - rect.left)/(voxelSize));
const y = Math.floor((py - rect.top)/(voxelSize));
if(x<0 || x>=gridWidth || y<0 || y>=gridHeight) return null;
return [x,y];
}
// Set voxel color
function setVoxel(x, y, color) {
if(x<0 || x>=gridWidth || y<0 || y>=gridHeight) return;
grid[y][x] = color;
}
// Toggle selection of one voxel:
function toggleSelect(x,y, shiftKey) {
const key = `${x},${y}`;
if(shiftKey){
// Select line between lastHovered and this voxel
if(lastHovered){
const [x0,y0] = lastHovered;
selection.clear();
// Bresenham line algorithm:
const linePoints = [];
function line(x0,y0,x1,y1){
let dx = Math.abs(x1-x0);
let sx = x0<x1 ? 1 : -1;
let dy = -Math.abs(y1-y0);
let sy = y0<y1 ? 1 : -1;
let err = dx+dy;
while(true){
linePoints.push([x0,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;}
}
}
line(x0,y0,x,y);
linePoints.forEach(([xx,yy])=>{
if(xx>=0 && xx<gridWidth && yy>=0 && yy<gridHeight) selection.add(`${xx},${yy}`);
});
return;
}
}
if(selection.has(key)){
selection.delete(key);
} else {
selection.add(key);
}
}
// Update position display
function updatePosDisplay(x,y){
if(x!==null && y!==null){
posDisplay.textContent = `Pos: (${x},${y}) Color: ${grid[y][x]||"none"}`;
} else {
posDisplay.textContent = "Pos: -";
}
}
// Copy selected voxels
function copySelection(){
if(selection.size === 0) return;
// Find min x, min y for relative copying
let xs = [], ys = [];
for(const pos of selection){
const [x,y] = pos.split(",").map(Number);
xs.push(x);
ys.push(y);
}
const minX = Math.min(...xs);
const minY = Math.min(...ys);
// Build clipboard object
clipboard = {
width: Math.max(...xs) - minX +1,
height: Math.max(...ys) - minY +1,
voxels: []
};
// Initialize voxels array with null
for(let y=0; y<clipboard.height; y++){
clipboard.voxels[y] = [];
for(let x=0; x<clipboard.width; x++){
clipboard.voxels[y][x] = null;
}
}
// Copy colors relative to minX,minY
for(const pos of selection){
const [x,y] = pos.split(",").map(Number);
clipboard.voxels[y-minY][x-minX] = grid[y][x];
}
alert(`Copied ${selection.size} voxels.`);
}
// Paste clipboard voxels at a position
function pasteClipboard(pasteX, pasteY){
if(!clipboard) return;
for(let y=0; y<clipboard.height; y++){
for(let x=0; x<clipboard.width; x++){
const col = clipboard.voxels[y][x];
const tx = pasteX+x;
const ty = pasteY+y;
if(tx>=0 && tx<gridWidth && ty>=0 && ty<gridHeight && col){
grid[ty][tx] = col;
}
}
}
drawGrid();
}
// Serialize grid to a compact format (RLE + Base64)
// Here simple JSON with compressed base64 string, could be improved
function serializeGrid(){
// Convert grid 2D array of colors to flat array of 0=empty + 1-true colors
// Instead, store colors as hex strings, or indices if we want palette.
// We'll do a simple method: create a palette of used colors, store indices.
let palette = [];
let indexes = [];
for(let y=0; y<gridHeight; y++) {
for(let x=0; x<gridWidth; x++) {
const c = grid[y][x];
if(c){
let idx = palette.indexOf(c);
if(idx<0){
palette.push(c);
idx = palette.length-1;
}
indexes.push(idx+1); // +1 to differentiate from empty=0
} else {
indexes.push(0);
}
}
}
// Now indexes is an array of numbers from 0 (empty) to palette.length
// RLE encode indexes
let rle = [];
let count = 1;
for(let i=1; i<=indexes.length; i++){
if(i<indexes.length && indexes[i] === indexes[i-1] && count<255){
count++;
} else {
rle.push(count, indexes[i-1]);
count=1;
}
}
// Convert rle array to bytes Uint8Array
const bytes = new Uint8Array(rle);
// Base64 encode
function base64FromByteArray(uint8) {
let binary = '';
const len = uint8.byteLength;
for (let i = 0; i < len; i++) {
binary += String.fromCharCode(uint8[i]);
}
return btoa(binary);
}
const dataStr = base64FromByteArray(bytes);
// Construct state object
const state = {
w: gridWidth,
h: gridHeight,
palette,
data: dataStr
};
return JSON.stringify(state);
}
// Deserialize grid from string
function deserializeGrid(str) {
try {
const state = JSON.parse(str);
if(!state.w || !state.h || !state.palette || !state.data) return false;
gridWidth = state.w;
gridHeight = state.h;
widthInput.value = gridWidth;
heightInput.value = gridHeight;
// Decode base64 to Uint8Array
function byteArrayFromBase64(b64) {
const binary = atob(b64);
const buffer = new Uint8Array(binary.length);
for(let i=0; i<binary.length; i++){
buffer[i] = binary.charCodeAt(i);
}
return buffer;
}
const bytes = byteArrayFromBase64(state.data);
// RLE decode
const indexes = [];
for(let i=0; i<bytes.length; i+=2){
const count = bytes[i];
const val = bytes[i+1];
for(let c=0; c<count; c++){
indexes.push(val);
}
}
if(indexes.length !== gridWidth*gridHeight) return false;
grid = [];
for(let y=0; y<gridHeight; y++){
const row = [];
for(let x=0; x<gridWidth; x++){
const v = indexes[y*gridWidth + x];
if(v === 0) row.push(null);
else row.push(state.palette[v-1]);
}
grid.push(row);
}
return true;
} catch(e) {
return false;
}
}
// Update URL hash for sharing
function updateURLHash() {
const state = serializeGrid();
// Compress and encode for URL safety - use encodeURIComponent for now
const encoded = encodeURIComponent(state);
location.hash = "#"+encoded;
}
// Load from URL hash
function loadFromHash() {
if(location.hash.length <= 1) return false;
const hash = location.hash.substring(1);
try {
const decoded = decodeURIComponent(hash);
const valid = deserializeGrid(decoded);
if(valid){
drawGrid();
return true;
}
} catch(e){}
return false;
}
// Event Handlers:
canvas.addEventListener("mousedown", ev=>{
const voxel = pixelToVoxel(ev.clientX, ev.clientY);
if(!voxel) return;
const [x,y] = voxel;
dragSelecting = true;
dragStart = voxel;
// If Ctrl/Meta held, toggle selection instead coloring
if(ev.ctrlKey || ev.metaKey){
toggleSelect(x,y, ev.shiftKey);
} else {
// Paint selected voxels with current color
if(selection.size > 0 && !(ev.shiftKey || ev.altKey)){
// Change color of all selected voxels
selection.forEach(pos=>{
const [sx,sy] = pos.split(",").map(Number);
setVoxel(sx, sy, colorInput.value);
});
} else {
setVoxel(x,y, colorInput.value);
if(!ev.shiftKey){
selection.clear();
selection.add(`${x},${y}`);
}
}
}
drawGrid();
updatePosDisplay(x,y);
});
canvas.addEventListener("mousemove", ev=>{
const voxel = pixelToVoxel(ev.clientX, ev.clientY);
if(!voxel){
updatePosDisplay(null,null);
return;
}
const [x,y] = voxel;
updatePosDisplay(x,y);
if(dragSelecting){
// Select drag area or paint rectangle between dragStart and current voxel
const x0 = Math.min(dragStart[0], x);
const x1 = Math.max(dragStart[0], x);
const y0 = Math.min(dragStart[1], y);
const y1 = Math.max(dragStart[1], y);
if(event.ctrlKey || event.metaKey){
// add to selection
for(let yy=y0; yy<=y1; yy++){
for(let xx=x0; xx<=x1; xx++){
selection.add(`${xx},${yy}`);
}
}
} else {
// paint rectangle with color
for(let yy=y0; yy<=y1; yy++){
for(let xx=x0; xx<=x1; xx++){
setVoxel(xx,yy, colorInput.value);
}
}
}
drawGrid();
}
lastHovered = voxel;
});
canvas.addEventListener("mouseup", ev=>{
dragSelecting = false;
});
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;
// Create new grid with old voxel data copied where possible
const newGrid = [];
for(let y=0; y<h; y++){
const row = [];
for(let x=0; x<w; x++){
row.push((y<gridHeight && x<gridWidth) ? grid[y][x] : null);
}
newGrid.push(row);
}
gridWidth = w;
gridHeight = h;
grid = newGrid;
widthInput.value = w;
heightInput.value = h;
selection.clear();
drawGrid();
updateURLHash();
};
widthInput.addEventListener("keydown", ev=>{
if(ev.key === "Enter") resizeBtn.click();
});
heightInput.addEventListener("keydown", ev=>{
if(ev.key === "Enter") resizeBtn.click();
});
colorInput.oninput = () => {
// Optionally, change color of selection
if(selection.size > 0){
selection.forEach(pos=>{
const [x,y] = pos.split(",").map(Number);
setVoxel(x,y,colorInput.value);
});
drawGrid();
updateURLHash();
}
};
copyBtn.onclick = copySelection;
pasteBtn.onclick = () => {
// Paste at first selected voxel or 0,0
let target = [0,0];
if(selection.size > 0){
const first = selection.values().next().value;
target = first.split(",").map(Number);
}
pasteClipboard(...target);
updateURLHash();
};
clearBtn.onclick = () => {
if(confirm("Clear all voxels?")){
resetGrid(gridWidth, gridHeight);
selection.clear();
drawGrid();
updateURLHash();
}
};
// Share button copies URL with current state to clipboard
shareBtn.onclick = () => {
updateURLHash();
navigator.clipboard.writeText(location.href).then(() => {
alert("Share URL copied to clipboard!");
});
};
// Keyboard shortcuts
window.addEventListener("keydown", ev=>{
if(ev.target.tagName === "INPUT") return; // avoid conflicts when typing
if((ev.ctrlKey || ev.metaKey) && ev.key.toLowerCase() === "c"){
ev.preventDefault();
copySelection();
}
if((ev.ctrlKey || ev.metaKey) && ev.key.toLowerCase() === "v"){
ev.preventDefault();
pasteBtn.click();
}
if(ev.key === "Delete" || ev.key === "Backspace"){
ev.preventDefault();
// Clear selected voxels
selection.forEach(pos=>{
const [x,y] = pos.split(",").map(Number);
setVoxel(x,y,null);
});
drawGrid();
updateURLHash();
}
});
// Init
if(!loadFromHash()){
resetGrid(gridWidth, gridHeight);
}
drawGrid();
updatePosDisplay(null,null);
})();
</script>
</body>
</html>
How to use the editor:
Click grid cells to paint with the selected color.
Shift + click on two voxels to select a line of voxels.
Line selection works with Shift + Ctrl/Cmd + click between two voxels (for easier selection, just Shift-click to select a line based on the last hovered voxel).
If you want me to add more features or explain how any part works, just ask!