const path = 'M0,0 C8,33.90861 25.90861,16 48,16 C70.09139,16 88,33.90861 88,56 C88,78.09139 105.90861,92 128,92 C150.09139,92 160,72 160,56 C160,40 148,24 128,24 C108,24 96,40 96,56 C96,72 105.90861,92 128,92 C154,93 168,78 168,56 C168,33.90861 185.90861,16 208,16 C230.09139,16 248,33.90861 248,56 C248,78.09139 230.09139,96 208,96 L48,96 C25.90861,96 8,78.09139 8,56 Z'; const pathElement = document.createElementNS('http://www.w3.org/2000/svg',"path"); pathElement.setAttributeNS(null, 'd', path);
const length = pathElement.getTotalLength(); const duration = 1000; // 动画总时长 const interval = length / duration; const canvas = document.querySelector('canvas'); const context = canvas.getContext('2d'); let time = 0, step = 0; const timer = setInterval(function() { if (time <= duration) { const x = parseInt(pathElement.getPointAtLength(step).x); const y = parseInt(pathElement.getPointAtLength(step).y); move(x, y); // 更新canvas所绘制图形的坐标 step++; } else { clearInterval(timer) } }, interval); function move(x, y) { context.clearRect(0, 0, canvas.width, canvas.height); context.beginPath(); context.arc(x, y, 25, 0, Math.PI*2, true); context.fillStyle = '#f0f'; context.fill(); context.closePath(); }
function customizePath(path, func) { const pathElement = document.createElementNS('http://www.w3.org/2000/svg',"path"); pathElement.setAttributeNS(null, 'd', path); const length = pathElement.getTotalLength(); const duration = 1000; const interval = length / duration; let time = 0, step = 0; const timer = setInterval(function() { if (time <= duration) { const x = parseInt(pathElement.getPointAtLength(step).x); const y = parseInt(pathElement.getPointAtLength(step).y); func(x, y); step++; } else { clearInterval(timer) } }, interval); } const path = 'M0,0 C8,33.90861 25.90861,16 48,16 C70.09139,16 88,33.90861 88,56 C88,78.09139 105.90861,92 128,92 C150.09139,92 160,72 160,56 C160,40 148,24 128,24 C108,24 96,40 96,56 C96,72 105.90861,92 128,92 C154,93 168,78 168,56 C168,33.90861 185.90861,16 208,16 C230.09139,16 248,33.90861 248,56 C248,78.09139 230.09139,96 208,96 L48,96 C25.90861,96 8,78.09139 8,56 Z'; const canvas = document.querySelector('canvas'); const context = canvas.getContext('2d'); function move(x, y) { context.clearRect(0, 0, canvas.width, canvas.height); context.beginPath(); context.arc(x, y, 25, 0, Math.PI*2, true); context.fillStyle = '#f0f'; context.fill(); context.closePath(); } customizePath(path, move);
实现思路大致如上所述,然而这并不是最终成果。当我们决定要在canvas制作自定义路径动画时,我们不仅要考虑如何实现,更要考虑性能优化,比如在这个实现思路中,我们是否可以减少不必要的渲染次数?帧率如何控制达到最优?等等。
虽然它们并不在这篇文章的讨论范围中,当也应当值得我们思考。
以上就是html5在Canvas中实现自定义路径动画详解的详细内容,更多请关注Gxl网其它相关文章!
查看更多关于html5在Canvas中实现自定义路径动画详解的详细内容...
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://www.haodehen.cn/did40649