<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Custom Lottery Ball Machine</title>
<style>
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background: linear-gradient(135deg, #3a3a3a, #121212);
color: #eee;
margin: 0;
padding: 0;
display: flex;
flex-direction: column;
min-height: 100vh;
overflow-x: hidden;
}
header {
background-color: #222;
padding: 1rem 2rem;
text-align: center;
font-size: 1.8rem;
letter-spacing: 1.2px;
font-weight: 700;
user-select: none;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.7);
}
main {
flex: 1;
padding: 1rem 2rem;
max-width: 1200px;
margin: 0 auto;
display: grid;
grid-template-columns: 1fr 1fr;
gap: 2rem;
align-items: start;
}
/* Controls area */
section.controls {
background-color: #222;
border-radius: 12px;
padding: 1rem 1.5rem;
box-shadow: 0 0 15px rgba(0, 255, 255, 0.3);
display: flex;
flex-direction: column;
gap: 1.25rem;
user-select: none;
}
section.controls h2 {
margin-top: 0;
font-weight: 700;
color: #0ff;
}
label {
display: flex;
flex-direction: column;
font-size: 1rem;
font-weight: 600;
color: #0ff;
margin-bottom: 0.3rem;
user-select: text;
}
input[type="number"],
input[type="text"],
input[type="file"],
select {
border-radius: 6px;
border: none;
padding: 0.6rem 0.8rem;
font-size: 1rem;
outline: none;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}
input[type="number"]::-webkit-inner-spin-button,
input[type="number"]::-webkit-outer-spin-button {
-webkit-appearance: none;
margin: 0;
}
button {
background: #0ff;
border: none;
border-radius: 8px;
padding: 0.8rem 1.2rem;
font-weight: 700;
color: #222;
font-size: 1.1rem;
cursor: pointer;
transition: transform 0.15s ease, box-shadow 0.2s ease;
user-select: none;
}
button:hover:not(:disabled) {
box-shadow: 0 0 12px #0ff;
transform: scale(1.05);
}
button:disabled {
background: #555;
cursor: not-allowed;
box-shadow: none;
transform: none;
color: #aaa;
}
/* Machine + track display */
section.machine-area {
background-color: #111;
border-radius: 12px;
box-shadow: 0 0 20px #00fff7;
padding: 1rem;
display: flex;
flex-direction: column;
align-items: center;
position: relative;
min-height: 500px;
}
.machine {
width: 280px;
height: 280px;
border-radius: 50%;
background: linear-gradient(145deg, #123844, #0af, #0af, #123844);
box-shadow: inset 0 10px 12px rgba(255, 255, 255, 0.2),
inset 0 -8px 10px rgba(0, 0, 0, 0.6),
0 0 30px #00f3ff77;
position: relative;
overflow: visible;
margin-bottom: 1.35rem;
}
.machine::before {
content: "";
position: absolute;
inset: 12px;
background: radial-gradient(circle at center, #2de3fccc, transparent 70%);
border-radius: 50%;
filter: blur(10px);
pointer-events: none;
}
.ball-container {
position: absolute;
inset: 20px;
border-radius: 50%;
overflow: visible;
display: flex;
justify-content: center;
align-items: center;
transform-style: preserve-3d;
}
/* The balls inside the machine will be arranged radially */
/* Balls */
.ball {
width: 48px;
height: 48px;
border-radius: 50%;
background: #0ff;
color: #003333;
font-weight: 700;
font-size: 1.2rem;
display: flex;
justify-content: center;
align-items: center;
user-select: none;
box-shadow:
inset 0 3px 5px rgba(0, 255, 255, 0.7),
0 2px 8px rgba(0, 255, 255, 0.7);
position: absolute;
cursor: default;
overflow: hidden;
text-align: center;
word-break: break-word;
}
.ball img {
max-width: 100%;
max-height: 100%;
object-fit: contain;
border-radius: 50%;
pointer-events: none;
user-select: none;
}
/* Track area */
.track {
width: 100%;
height: 140px;
border-radius: 8px;
background: linear-gradient(90deg, #222 20%, #0ff 40%, #222 60%);
box-shadow:
inset 0 -8px 8px #0ff,
0 15px 30px #0ff44;
position: relative;
overflow: hidden;
}
/* rolling ball */
.rolling-ball {
width: 50px;
height: 50px;
border-radius: 50%;
background: #0ff;
color: #003333;
font-weight: 700;
font-size: 1.4rem;
display: flex;
justify-content: center;
align-items: center;
box-shadow:
inset 0 4px 6px rgba(0, 255, 255, 0.9),
0 6px 15px rgba(0, 255, 255, 0.9);
position: absolute;
top: 50%;
transform: translateY(-50%);
user-select: none;
pointer-events: none;
overflow: hidden;
white-space: nowrap;
}
.rolling-ball img {
max-width: 100%;
max-height: 100%;
object-fit: contain;
border-radius: 50%;
pointer-events: none;
user-select: none;
}
/* Form textarea */
textarea {
resize: vertical;
min-height: 60px;
max-height: 120px;
border-radius: 6px;
border: none;
padding: 0.6rem 0.8rem;
font-size: 1rem;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
outline: none;
}
@media (max-width: 900px) {
main {
grid-template-columns: 1fr;
}
section.machine-area {
min-height: 440px;
}
}
</style>
</head>
<body>
<header>Custom Lottery Ball Machine</header>
<main>
<section class="controls" aria-label="Controls">
<h2>Machine Settings</h2>
<label for="num-balls">
Number of balls in machine (1 - 50):
<input type="number" id="num-balls" min="1" max="50" value="10" />
</label>
<label for="spin-length">
Spin length (seconds, 1 - 1000):
<input type="number" id="spin-length" min="1" max="1000" value="5" />
</label>
<label for="spin-speed">
Spin speed (1 - 1,000,000):
<input type="number" id="spin-speed" min="1" max="1000000" value="500000" />
</label>
<h2>Customize Ball</h2>
<label for="custom-text">
Enter text prompt for ball customization:
<textarea id="custom-text" placeholder="Write something to appear on/inside the ball..."></textarea>
</label>
<label for="custom-image">
Or upload an image for the ball:
<input type="file" id="custom-image" accept="image/*" />
</label>
<button id="add-ball-btn" disabled>Add Custom Ball to Machine</button>
<button id="spin-btn" disabled>Spin Machine</button>
</section>
<section class="machine-area" aria-label="Lottery Ball Machine Display">
<div class="machine" aria-live="polite" aria-atomic="true" aria-relevant="additions removals">
<div class="ball-container" id="ball-container"></div>
</div>
<div class="track" aria-label="Ball track"></div>
</section>
</main>
<script>
(() => {
const numBallsInput = document.getElementById('num-balls');
const spinLengthInput = document.getElementById('spin-length');
const spinSpeedInput = document.getElementById('spin-speed');
const customTextInput = document.getElementById('custom-text');
const customImageInput = document.getElementById('custom-image');
const addBallBtn = document.getElementById('add-ball-btn');
const spinBtn = document.getElementById('spin-btn');
const ballContainer = document.getElementById('ball-container');
const track = document.querySelector('.track');
// State
let balls = [];
let spinning = false;
let rollingBall = null; // The ball rolling onto the track after spin
let rollingAnimation = null;
/**
* Ball object structure:
* {
* id: Number,
* display: String (text or '' if image),
* imageSrc: String (null or URL),
* }
*/
// Helper: create a ball DOM elem from ball data
function createBallElement(ball) {
const div = document.createElement('div');
div.className = 'ball';
div.dataset.id = ball.id;
if (ball.imageSrc) {
const img = document.createElement('img');
img.src = ball.imageSrc;
img.alt = `Custom ball image ${ball.id}`;
div.appendChild(img);
} else {
div.textContent = ball.display;
div.title = `Ball #${ball.display}`;
}
return div;
}
// Position balls radially inside the machine
function positionBalls() {
const count = balls.length;
const radius = 110; // radius from center in px
// Clear container first
ballContainer.innerHTML = '';
balls.forEach((ball, i) => {
const elem = createBallElement(ball);
ballContainer.appendChild(elem);
const angle = (2 * Math.PI / count) * i - Math.PI / 2; // start from top
const x = radius * Math.cos(angle);
const y = radius * Math.sin(angle);
elem.style.left = `calc(50% + ${x}px - 24px)`; // 48px ball width half = 24
elem.style.top = `calc(50% + ${y}px - 24px)`;
});
}
// Generate initial balls (numerical only)
function generateInitialBalls(n) {
balls = [];
for (let i = 1; i <= n; i++) {
balls.push({
id: i,
display: i.toString(),
imageSrc: null,
});
}
positionBalls();
spinBtn.disabled = balls.length === 0 || spinning;
}
// Validate inputs and enable buttons accordingly
function validateInputs() {
const numBallsValid =
numBallsInput.value &&
+numBallsInput.value >= 1 &&
+numBallsInput.value <= 50;
const spinLengthValid =
spinLengthInput.value &&
+spinLengthInput.value >= 1 &&
+spinLengthInput.value <= 1000;
const spinSpeedValid =
spinSpeedInput.value &&
+spinSpeedInput.value >= 1 &&
+spinSpeedInput.value <= 1000000;
const customText = customTextInput.value.trim();
const hasText = customText.length > 0;
const hasImage = customImageInput.files.length === 1;
addBallBtn.disabled = !(hasText || hasImage) || balls.length >= 50 || spinning;
spinBtn.disabled = balls.length === 0 || spinning || !numBallsValid || !spinLengthValid || !spinSpeedValid;
}
// Add a custom ball from text or image
function addCustomBall() {
if (balls.length >= 50) {
alert('Maximum 50 balls allowed in the machine.');
return;
}
const text = customTextInput.value.trim();
const imgFile = customImageInput.files[0];
if (!text && !imgFile) {
alert('Please enter a text or upload an image to customize the ball.');
return;
}
// Create new ball object
const id = balls.length > 0 ? balls[balls.length - 1].id + 1 : 1;
if (imgFile) {
// Read image as Data URL
const reader = new FileReader();
reader.onload = () => {
balls.push({
id,
display: '',
imageSrc: reader.result,
});
positionBalls();
spinBtn.disabled = false;
resetCustomizationInputs();
};
reader.readAsDataURL(imgFile);
} else {
balls.push({
id,
display: text,
imageSrc: null,
});
positionBalls();
spinBtn.disabled = false;
resetCustomizationInputs();
}
}
function resetCustomizationInputs() {
customTextInput.value = '';
customImageInput.value = '';
addBallBtn.disabled = true;
}
// Animate spinning of balls inside machine. Controlled via spin length and speed.
// The balls will rotate around the center at speed controlled by "speed" for "length" seconds.
async function spinMachine() {
if (spinning || balls.length === 0) return;
spinning = true;
spinBtn.disabled = true;
addBallBtn.disabled = true;
numBallsInput.disabled = true;
spinLengthInput.disabled = true;
spinSpeedInput.disabled = true;
customTextInput.disabled = true;
customImageInput.disabled = true;
const length = Math.min(Math.max(+spinLengthInput.value, 1), 1000);
const speed = Math.min(Math.max(+spinSpeedInput.value, 1), 1000000);
let startTime = null;
let angleOffset = 0;
const count = balls.length;
const radius = 110;
return new Promise((resolve) => {
function animate(time) {
if (!startTime) startTime = time;
const elapsed = (time - startTime) / 1000;
// Spin speed controls degrees per second:
// Normalize speed to something visually sensible:
// Map 1 - 1,000,000 to 0.1 - 25 rotations per second (360deg * rotations)
const rotationsPerSecond = 0.1 + ((speed - 1) / (1000000 - 1)) * (25 - 0.1);
const degreesPerSecond = rotationsPerSecond * 360;
angleOffset = (degreesPerSecond * elapsed) % 360;
// Position balls dynamically with rotation angle offset
ballContainer.childNodes.forEach((elem, i) => {
const angleRad =
((2 * Math.PI) / count) * i - Math.PI / 2 + (angleOffset * Math.PI) / 180;
const x = radius * Math.cos(angleRad);
const y = radius * Math.sin(angleRad);
elem.style.left = `calc(50% + ${x}px - 24px)`;
elem.style.top = `calc(50% + ${y}px - 24px)`;
});
if (elapsed < length) {
requestAnimationFrame(animate);
} else {
// Stop spinning, pick winner (ball at top)
// ball closest to angle -90deg = top
let closestIdx = 0;
let closestDiff = Infinity;
balls.forEach((ball, i) => {
const baseAngle = ((2 * Math.PI) / count) * i - Math.PI / 2;
// final angle = baseAngle + angleOffset (converted to rad)
const finalAngle = (baseAngle + (angleOffset * Math.PI) / 180) % (2 * Math.PI);
// Find difference from top (-Pi/2 == 3Pi/2 mod 2Pi)
// easier if we normalize top to 0 rad by subtracting -Pi/2:
const adjusted = (finalAngle + 2 * Math.PI) % (2 * Math.PI);
// top is at 3Pi/2 == 4.712 rad which mod 2Pi = 4.712 - 6.283 = -1.57 ~ same as -PI/2
// Instead, we check distance from 3Pi/2 directly mod 2Pi
// But simpler: Because we normalized angle in range 0-2Pi, top is at 3Pi/2 (4.712)
// Calculate shortest distance around circle:
let diff = Math.min(
Math.abs(adjusted - (3 * Math.PI) / 2),
2 * Math.PI - Math.abs(adjusted - (3 * Math.PI) / 2)
);
if (diff < closestDiff) {
closestDiff = diff;
closestIdx = i;
}
});
const winner = balls[closestIdx];
// Remove all balls from machine except winner to prepare rolling out
ballContainer.innerHTML = '';
// Animate rolling winner out:
rollOutBall(winner).then(() => {
// Reset UI after roll out
spinning = false;
spinBtn.disabled = false;
addBallBtn.disabled = false;
numBallsInput.disabled = false;
spinLengthInput.disabled = false;
spinSpeedInput.disabled = false;
customTextInput.disabled = false;
customImageInput.disabled = false;
resolve();
});
}
}
requestAnimationFrame(animate);
});
}
// Animate winner ball rolling out onto the track left to right
function rollOutBall(ball) {
return new Promise((resolve) => {
if (rollingBall) {
// Clear previous rolling ball
rollingBall.remove();
}
const rb = document.createElement('div');
rb.className = 'rolling-ball';
if (ball.imageSrc) {
const img = document.createElement('img');
img.src = ball.imageSrc;
img.alt = `Winner ball image #${ball.id}`;
rb.appendChild(img);
} else {
rb.textContent = ball.display;
rb.title = `Winner Ball #${ball.display}`;
}
track.appendChild(rb);
rollingBall = rb;
// Calculate animation distance (track width - ball width - small margin)
const trackWidth = track.clientWidth;
const ballWidth = rb.offsetWidth;
const marginRight = 20;
let start = performance.now();
function animate(time) {
const elapsed = (time - start) / 1000; // seconds
const duration = 4; // seconds
if (elapsed < duration) {
// Linear animation from left to right
const x = (elapsed / duration) * (trackWidth - ballWidth - marginRight);
rb.style.left = `${x}px`;
requestAnimationFrame(animate);
} else {
// End position
rb.style.left = `${trackWidth - ballWidth - marginRight}px`;
resolve();
}
}
// Start from left off screen slightly
rb.style.left = `0px`;
requestAnimationFrame(animate);
});
}
// Event listeners
numBallsInput.addEventListener('change', () => {
let val = +numBallsInput.value;
if (isNaN(val) || val < 1) val = 1;
else if (val > 50) val = 50;
numBallsInput.value = val.toString();
generateInitialBalls(val);
validateInputs();
});
spinLengthInput.addEventListener('input', () => {
let val = +spinLengthInput.value;
if (isNaN(val) || val < 1) val = 1;
else if (val > 1000) val = 1000;
spinLengthInput.value = val.toString();
validateInputs();
});
spinSpeedInput.addEventListener('input', () => {
let val = +spinSpeedInput.value;
if (isNaN(val) || val < 1) val = 1;
else if (val > 1000000) val = 1000000;
spinSpeedInput.value = val.toString();
validateInputs();
});
customTextInput.addEventListener('input', () => {
if (customTextInput.value.trim().length > 0) {
// Clear file input to enforce either text or image
customImageInput.value = '';
}
validateInputs();
});
customImageInput.addEventListener('change', () => {
if (customImageInput.files.length === 1) {
// Clear text input to enforce either text or image
customTextInput.value = '';
}
validateInputs();
});
addBallBtn.addEventListener('click', (e) => {
e.preventDefault();
addCustomBall();
});
spinBtn.addEventListener('click', (e) => {
e.preventDefault();
if (balls.length === 0) {
alert('There are no balls in the machine to spin.');
return;
}
spinMachine();
});
// Initialize
generateInitialBalls(+numBallsInput.value);
validateInputs();
})();
</script>
</body>
</html>
Explanation:
- The machine starts with a default number of balls (10), with numbers (1 to count).
- You may change the number of balls (1 to 50). Changing this resets the balls to numeric balls.
- You can add custom balls by inputting text or uploading an image (but not both simultaneously).
- Custom balls are added with a unique incremental
id.
- Spin length is configurable from 1 second to 1000 seconds.
- Spin speed input from 1 to 1,000,000, normalized internally for rotational velocity.
- Press Spin to rotate the balls radially around the machine for the chosen duration and speed.
- After spinning finishes, the ball currently closest to the "top" of the circular machine is selected as the winner.
- The winner ball rolls smoothly from the machine onto the track (animated left to right).
- Buttons and inputs are disabled/enabled logically during spins and other user interactions.
- The UI is dark-themed with cyan/blue highlights, with a realistic glowing "machine" and track.
- Accessibility features like ARIA labels and roles included.
- Images on balls scale inside the ball circle. Text balls show text centered.
- The spin rotation is done via
requestAnimationFrame and an angle offset update.
Open this file in a modern browser to try the lottery ball machine widget directly.