randomLang
by mcoirad
HTML
<script src="https://cdn.jsdelivr.net/npm/@svgdotjs/svg.js"></script>
<div id="canvas"></div>
CSS
body { background: #f5f5f5; }
#canvas { margin: 20px auto; width: 600px; height: 600px; border: 1px solid #ccc; }
JavaScript
// Assuming svg.js is loaded and you have a container <div id="drawing"></div>
const draw = SVG().addTo('#canvas').size(400, 400)
function randomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min
}
function randomChoice(arr) {
return arr[Math.floor(Math.random() * arr.length)]
}
function generatePrimitive(type) {
if (type === 'rectangle') {
const width = randomInt(20, 60)
const height = randomInt(10, 40)
return draw.rect(width, height).fill('none').stroke({ width: 2, color: 'black' })
} else if (type === 'triangle') {
const size = randomInt(30, 50)
let points = '0,0 ' + size + ',0 ' + (size / 2) + ',' + size
return draw.polygon(points).fill('none').stroke({ width: 2, color: 'black' })
} else if (type === 'line') {
const length = randomInt(30, 80)
const isVertical = Math.random() < 0.5
return draw.line(0, 0, isVertical ? 0 : length, isVertical ? length : 0).stroke({ width: 2, color: 'black' })
} else if (type === 'circle') {
const r = randomInt(15, 30)
return draw.circle(r * 2).fill('none').stroke({ width: 2, color: 'black' })
}
}
function maybeModify(primitive, type) {
if (type === 'rectangle' || type === 'triangle') {
if (Math.random() < 0.5) primitive.attr({ 'stroke-dasharray': '5,5' })
}
if (type === 'circle') {
if (Math.random() < 0.5) {
const bbox = primitive.bbox()
primitive.clipWith(draw.rect(bbox.width, bbox.height / 2).move(bbox.x, bbox.y))
}
}
}
function generateGlyph() {
const group = draw.group()
const numParts = randomInt(2, 4)
const yOffset = 0
for (let i = 0; i < numParts; i++) {
const type = randomChoice(['rectangle', 'triangle', 'line', 'circle'])
const part = generatePrimitive(type)
maybeModify(part, type)
part.move(50, i * 60)
group.add(part)
}
return group
}
// Example usage:
generateGlyph()