SVG Drawing - JS example
by PrismDan
HTML
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200">
<polygon id="target" points="99.87,156.58 44.62,185.62 55.17,124.1 10.48,80.54 72.25,71.56 99.87,15.59 127.49,71.56 189.26,80.54 144.56,124.1 155.11,185.62"/>
<polygon class="placeholder" points="99.87,156.58 44.62,185.62 55.17,124.1 10.48,80.54 72.25,71.56 99.87,15.59 127.49,71.56 189.26,80.54 144.56,124.1 155.11,185.62"/>
</svg>
<input id="progress" type="range" min="0" max="100" />
<span>Set drawing progress</span>
CSS
body {
background-color: rgb(2, 62, 80);
min-height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
font-family: monospace;
color: #fff;
}
svg {
width: 120px;
max-width: 90vw;
height: auto;
transform-origin: center;
}
polygon {
fill: none;
stroke: #fff;
stroke-width: 10;
stroke-linecap: round;
}
polygon.placeholder {
stroke-dashoffset: 0;
opacity: .15;
}
label {
position: relative;
cursor: pointer;
}
label:after {
content: 'Click to draw';
position: absolute;
color: #fff;
font-family: monospace;
top: calc(100% + 1em);
left: 0;
width: 100%;
text-align: center;
}
#progress {
margin: 1em 0;
}
JavaScript
const target = document.getElementById('target');
const progressInput = document.getElementById('progress');
const pathLength = target.getTotalLength();
target.style.strokeDasharray = pathLength;
const update = () => {
target.style.strokeDashoffset = pathLength * ((100 - progressInput.value) / 100);
};
progressInput.addEventListener('input', (e) => {
update();
});
update();