I am trying to figure out a way to code a letter tracing activity for kids wherein the user has to press and move the cursor, and along the cursor's pointer the alphabet gets colored. I tried using svg's stroke-dashedoffset attribute to color the insides of the svg along the pointer's position.
var svg = document.querySelectorAll('svg g line');
var elem1 = document.querySelector("#svg_2");
var elem2 = document.querySelector("#svg_3");
var len1 = svg[0].getTotalLength()
var len2 = svg[1].getTotalLength()
let mouseDraw = false
// only tackling the left stroke of the alphabet 'v' for now
elem1.addEventListener("mousedown", (evt) => {
// console.log('mousedown')
mouseDraw = true
})
elem1.addEventListener('mouseup', () => {
// console.log('mouseup')
mouseDraw = false
})
elem1.addEventListener('mousemove', (evt) => {
if(mouseDraw){
// console.log('mousemove')
var e = evt.target;
var dim = e.getBoundingClientRect();
var y = evt.pageY - dim.height;
// console.log(y);
svg[2].style.strokeDashoffset = y + 'px';
}
})
<?xml version="1.0"?>
<svg width="640" height="480" xmlns="http://www.w3.org/2000/svg" xmlns:svg="http://www.w3.org/2000/svg">
<!-- Created with SVG-edit - https://github.com/SVG-Edit/svgedit-->
<g class="layer1">
<title>Layer 1</title>
<line fill="none" id="svg_2" stroke="#bbb" stroke-width="10" x1="213" x2="248" y1="134" y2="226" st/>
<line fill="none" id="svg_3" stroke="#bbb" stroke-width="10" x1="249" x2="297" y1="226" y2="133"/>
</g>
<g class="layer2">
<title>Layer 1</title>
<line fill="none" id="svg_2" stroke="#000" stroke-width="10" x1="213" x2="248" y1="134" y2="226" style="stroke-dashoffset:98.4px;stroke-dasharray:98.4px"/>
<line fill="none" id="svg_3" stroke="#000" stroke-width="10" x1="249" x2="297" y1="226" y2="133" style="stroke-dashoffset:104.6px;stroke-dasharray:104.6px"/>
</g>
</svg>
What I' struggling is to map the pointer's position accurately. Any help in this regard is very much appreciated! Thanks!