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
| import rAFWithFPS from "@/rAFWithFPS";
const getRenderWidthOfText = (text, font = '') => { const canvas = document.createElement('canvas') const ctx = canvas.getContext('2d') ctx.font = font return ctx.measureText(text).width }
const runAttr = ({ targetNode, scrollNum, duration, easing }) => { let fixed = 0 const strNum = scrollNum + '' const val = strNum.lastIndexOf('.') if (val !== -1) fixed = strNum.length - (val + 1) rAFWithFPS(progress => { targetNode.innerHTML = (easing(progress) * scrollNum).toFixed(fixed) }, duration) } export default { bind (el, { value: { lightClass = '', easing = x => Math.sin((x * Math.PI) / 2), duration = 500 } = {} }, vNode) { const defaultStyle = { display: 'inline-block', 'text-align': 'center', 'box-sizing': 'content-box' } vNode.context.$nextTick(() => { const font = getComputedStyle(el).font const replaceStr = el.innerText.replaceAll(/[\d\.]+/g, $1 => { if (isNaN(+$1)) return $1 const spanWidth = Math.floor(getRenderWidthOfText($1.trim(), font)) const style = { ...defaultStyle, width: `${ spanWidth }px` } let styleStr = Object .entries(style) .reduce((result, [ key, value ]) => result + `${ key }:${ value };`, '') return `<span scroll-num="${ $1 }" class="${ lightClass }" style="${ styleStr }"> </span>` }) el.innerHTML = replaceStr || ' ' const allLightNode = el.querySelectorAll('span[scroll-num]') for (const node of allLightNode) { const scrollNum = +node.getAttribute('scroll-num') runAttr({ targetNode: node, scrollNum, easing, duration, }) } }) } }
|