Last active
October 16, 2024 08:46
-
-
Save MstrVLT/e50acb42973114ed9c4617492067f01c to your computer and use it in GitHub Desktop.
d3 transition + vue
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script setup> | |
import { useTemplateRef } from 'vue'; | |
import SelectionJoin from './components/SelectionJoin.vue'; | |
const SelectionJoinRef = useTemplateRef('el'); | |
const update = () => | |
SelectionJoinRef && SelectionJoinRef.value.update(); | |
</script> | |
<template> | |
<SelectionJoin ref="el" :width="300" @click="update" /> | |
</template> | |
<style scoped></style> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script setup> | |
import { computed, onMounted, ref, toValue, useTemplateRef, watch } from 'vue'; | |
import * as d3 from 'd3'; | |
import _ from 'lodash'; | |
const props = defineProps({ | |
width: Number, | |
}); | |
const randomLetters = () => { | |
return d3 | |
.shuffle('abcdefghijklmnopqrstuvwxyz'.split('')) | |
.slice(0, Math.floor(6 + Math.random() * 20)) | |
.sort(); | |
}; | |
const svgRef = useTemplateRef('svg'); | |
const update = computed(() => { | |
return _.throttle( | |
() => { | |
if (svgRef.value === null) return; | |
const s = d3.select(svgRef.value); | |
const t = s.transition().duration(750); | |
s.selectAll('text') | |
.data(randomLetters(), (d) => d) | |
.join( | |
(enter) => | |
enter | |
.append('text') | |
.attr('fill', 'green') | |
.attr('x', (d, i) => i * 16) | |
.attr('y', -30) | |
.text((d) => d) | |
.call((enter) => enter.transition(t).attr('y', 0)), | |
(update) => | |
update | |
.attr('fill', 'black') | |
.attr('y', 0) | |
.call((update) => | |
update.transition(t).attr('x', (d, i) => i * 16) | |
), | |
(exit) => | |
exit | |
.attr('fill', 'brown') | |
.call((exit) => exit.transition(t).attr('y', 30).remove()) | |
); | |
}, | |
750 + 50, | |
{ leading: true, trailing: false } | |
); | |
}); | |
defineExpose({ | |
update, | |
}); | |
watch([svgRef, () => props.width], ([svg, width]) => { | |
if (svg === null) return; | |
d3.select(svg) | |
.attr('width', width) | |
.attr('height', 33) | |
.attr('viewBox', `0 -20 ${width} 33`); | |
update.value(); | |
}); | |
</script> | |
<template> | |
<svg ref="svg"></svg> | |
</template> | |
<style scoped></style> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment