1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
| d3.selectAll('path') .attr('test', function () { let d = d3.select(this).attr('d'); let id = d3.select(this).attr('id');
if (id === 'SvgjsPath1096') { console.log(`%c ${d}`, 'color:red'); } else { console.log(d); } let paths = dAttrToPath(d) if (paths.length <= 0) { return false; } let ball = d3.select(this.parentNode) .append('circle') .attr('r', 10) .attr('fill', 'red') .classed('ball', true)
play(paths, ball, 1) })
function play(paths, ball, i) { if (i === 1) { ball.attr('transform', `translate(${paths[0][0]}, ${paths[0][1]})`) } let currentCoordinate = i === 0 ? paths[0] : paths[i - 1] let nextCoordinate = paths[i] let duration = computeSpeed(currentCoordinate, nextCoordinate) try { ball.transition() .attr('transform', `translate(${paths[i][0]}, ${paths[i][1]})`) .duration(duration) .ease(d3.easeLinear) .on('end', async function () { if (i === paths.length - 1) { play(paths, ball, 1) } else { play(paths, ball, i + 1) } }) } catch (e) { console.log(`translate(${paths[i][0]}, ${paths[i][1]})`); } }
function computeSpeed(coordinate1, coordinate2) { let distance = Math.sqrt(Math.pow(coordinate1[0] - coordinate2[0], 2) + Math.pow(coordinate1[1] - coordinate2[1], 2)) return distance * 20; }
function dAttrToPath(dValue) { let coordinates = []; if (dValue.includes('C') || dValue.includes('Z')) { return coordinates; } dValue.replace('M', '').split('L').forEach(d => { let coord = d.trim().split(' '); if (coord.length > 1) { coordinates.push(d.trim().split(' ')) } }) for (let i = 1; i < coordinates.length; i ++) { if (coordinates[i - 1] && coordinates[i][0] === coordinates[i - 1][0] && coordinates[i][1] === coordinates[i - 1][1]) { delete coordinates[i] } }
let result = []; coordinates.forEach(d => result.push(d))
return result; }
|