广东专注网站建设企业,彩票自己开盘做网站,建设部网站王尚春,更换网站服务器前端技术探索系列#xff1a;HTML5 SVG 集成详解 #x1f3a8;
开篇寄语 #x1f44b;
前端开发者们#xff0c;
在前五篇文章中#xff0c;我们探讨了 HTML5 的多个特性。今天#xff0c;让我们深入了解 SVG 的魅力#xff0c;看看如何创建可缩放的矢量图形。
一、…前端技术探索系列HTML5 SVG 集成详解
开篇寄语
前端开发者们
在前五篇文章中我们探讨了 HTML5 的多个特性。今天让我们深入了解 SVG 的魅力看看如何创建可缩放的矢量图形。
一、SVG 基础入门 ✨
1. SVG 语法基础
!-- 内联 SVG --
svg width200 height200 viewBox0 0 200 200!-- 基础图形 --circle cx100 cy100 r50 fillblue /rect x50 y50 width100 height100 fillred opacity0.5 /path dM10 10 H 90 V 90 H 10 Z fillnone strokeblack /
/svg2. 基础图形绘制
svg width400 height400!-- 矩形 --rectx10 y10width100 height50fillbluestrokeblackstroke-width2rx10 ry10/!-- 圆形 --circlecx200 cy50r40fillredstrokedarkredstroke-width2/!-- 椭圆 --ellipsecx300 cy50rx60 ry30fillgreen/!-- 线条 --linex110 y1100x2100 y2150strokepurplestroke-width2/!-- 多边形 --polygonpoints200,100 250,150 150,150fillorange/
/svg3. 复用与组织
!-- 定义可重用元素 --
svgdefs!-- 渐变定义 --linearGradient idgradient x10% y10% x2100% y20%stop offset0% stylestop-color:rgb(255,255,0); /stop offset100% stylestop-color:rgb(255,0,0); //linearGradient!-- 符号定义 --symbol idstar viewBox0 0 32 32path dM16 0 L20 12 L32 12 L22 20 L26 32 L16 24 L6 32 L10 20 L0 12 L12 12 Z //symbol/defs!-- 使用定义的元素 --rect width200 height100 fillurl(#gradient) /use href#star x50 y50 width32 height32 fillgold /
/svg二、SVG 动画技术
1. SMIL 动画
svg width300 height300circle cx150 cy150 r50 fillblue!-- 位置动画 --animateTransformattributeNametransformtypetranslatevalues0,0; 50,0; 0,0dur2srepeatCountindefinite/!-- 颜色动画 --animateattributeNamefillvaluesblue;red;bluedur3srepeatCountindefinite/!-- 路径动画 --animateMotionpathM 0 0 H 100 V 100 H 0 Zdur4srepeatCountindefinite//circle
/svg2. CSS 动画
style
.rotating-star {animation: rotate 3s linear infinite;transform-origin: center;
}keyframes rotate {from { transform: rotate(0deg); }to { transform: rotate(360deg); }
}.pulsing-circle {animation: pulse 2s ease-in-out infinite;
}keyframes pulse {0% { transform: scale(1); }50% { transform: scale(1.2); }100% { transform: scale(1); }
}
/stylesvg width200 height200use href#star classrotating-star x50 y50 width100 height100 /circle classpulsing-circle cx100 cy100 r50 fillpurple /
/svg3. JavaScript 动画
class SVGAnimator {constructor(element) {this.element element;this.animations new Map();}// 添加动画animate(properties, duration, easing linear) {const startTime performance.now();const initialValues {};// 获取初始值for (const prop in properties) {initialValues[prop] parseFloat(this.element.getAttribute(prop));}const animation {startTime,duration,initialValues,targetValues: properties,easing};this.animations.set(animation, true);this.startAnimation();}// 动画循环startAnimation() {if (this.animationFrame) return;const animate (currentTime) {let hasRunning false;this.animations.forEach((isRunning, animation) {if (!isRunning) return;const elapsed currentTime - animation.startTime;const progress Math.min(elapsed / animation.duration, 1);if (progress 1) {hasRunning true;this.updateProperties(animation, progress);} else {this.animations.delete(animation);}});if (hasRunning) {this.animationFrame requestAnimationFrame(animate);} else {this.animationFrame null;}};this.animationFrame requestAnimationFrame(animate);}// 更新属性updateProperties(animation, progress) {for (const prop in animation.targetValues) {const initial animation.initialValues[prop];const target animation.targetValues[prop];const current initial (target - initial) * progress;this.element.setAttribute(prop, current);}}
}三、SVG 交互实现 ️
1. 事件处理
class SVGInteraction {constructor(svg) {this.svg svg;this.elements new Map();this.setupEvents();}setupEvents() {this.svg.addEventListener(click, this.handleClick.bind(this));this.svg.addEventListener(mousemove, this.handleMouseMove.bind(this));}// 获取 SVG 坐标getSVGPoint(event) {const point this.svg.createSVGPoint();point.x event.clientX;point.y event.clientY;return point.matrixTransform(this.svg.getScreenCTM().inverse());}// 添加可交互元素addInteractiveElement(element, handlers) {this.elements.set(element, handlers);element.addEventListener(mouseenter, () {if (handlers.hover) {handlers.hover(element, true);}});element.addEventListener(mouseleave, () {if (handlers.hover) {handlers.hover(element, false);}});}handleClick(event) {const point this.getSVGPoint(event);this.elements.forEach((handlers, element) {if (this.isPointInElement(point, element) handlers.click) {handlers.click(element);}});}handleMouseMove(event) {const point this.getSVGPoint(event);this.elements.forEach((handlers, element) {if (this.isPointInElement(point, element) handlers.move) {handlers.move(element, point);}});}isPointInElement(point, element) {const bbox element.getBBox();return (point.x bbox.x point.x bbox.x bbox.width point.y bbox.y point.y bbox.y bbox.height);}
}2. 滤镜效果
svg width400 height400defs!-- 高斯模糊 --filter idblurfeGaussianBlur stdDeviation2 //filter!-- 阴影效果 --filter idshadowfeDropShadow dx2 dy2 stdDeviation2 //filter!-- 发光效果 --filter idglowfeGaussianBlur stdDeviation2 resultcoloredBlur /feMergefeMergeNode incoloredBlur /feMergeNode inSourceGraphic //feMerge/filter/defs!-- 使用滤镜 --circle cx100 cy100 r50 fillpurple filterurl(#glow) /
/svg四、实践项目动态 LOGO 生成器
class LogoGenerator {constructor(container) {this.container container;this.svg document.createElementNS(http://www.w3.org/2000/svg, svg);this.setup();}setup() {this.svg.setAttribute(width, 300);this.svg.setAttribute(height, 300);this.container.appendChild(this.svg);// 定义滤镜和渐变this.defineFilters();this.defineGradients();}defineFilters() {const defs document.createElementNS(http://www.w3.org/2000/svg, defs);// 添加发光效果const glowFilter filter idlogo-glowfeGaussianBlur stdDeviation2 resultblur /feFlood flood-colorrgba(0,0,255,0.3) resultcolor /feComposite incolor in2blur operatorin /feMergefeMergeNode /feMergeNode inSourceGraphic //feMerge/filter;defs.innerHTML glowFilter;this.svg.appendChild(defs);}defineGradients() {const defs this.svg.querySelector(defs);// 添加渐变const gradient linearGradient idlogo-gradient x10% y10% x2100% y20%stop offset0% stylestop-color:#4CAF50 /stop offset100% stylestop-color:#2196F3 //linearGradient;defs.innerHTML gradient;}// 生成 LogogenerateLogo(text, options {}) {const {fontSize 48,fontFamily Arial,color url(#logo-gradient),useGlow true} options;// 清空现有内容while (this.svg.lastChild) {this.svg.removeChild(this.svg.lastChild);}// 重新添加 defsthis.defineFilters();this.defineGradients();// 创建文本元素const textElement document.createElementNS(http://www.w3.org/2000/svg, text);textElement.textContent text;textElement.setAttribute(x, 150);textElement.setAttribute(y, 150);textElement.setAttribute(text-anchor, middle);textElement.setAttribute(dominant-baseline, middle);textElement.setAttribute(font-size, fontSize);textElement.setAttribute(font-family, fontFamily);textElement.setAttribute(fill, color);if (useGlow) {textElement.setAttribute(filter, url(#logo-glow));}// 添加动画const animation document.createElementNS(http://www.w3.org/2000/svg, animateTransform);animation.setAttribute(attributeName, transform);animation.setAttribute(type, scale);animation.setAttribute(values, 1;1.1;1);animation.setAttribute(dur, 2s);animation.setAttribute(repeatCount, indefinite);textElement.appendChild(animation);this.svg.appendChild(textElement);return this;}// 导出 SVGexport() {const serializer new XMLSerializer();return serializer.serializeToString(this.svg);}// 导出 PNGasync exportPNG() {return new Promise((resolve, reject) {const image new Image();image.onload () {const canvas document.createElement(canvas);canvas.width 300;canvas.height 300;const ctx canvas.getContext(2d);ctx.drawImage(image, 0, 0);resolve(canvas.toDataURL(image/png));};image.onerror reject;const svgBlob new Blob([this.export()], { type: image/svgxml });image.src URL.createObjectURL(svgBlob);});}
}// 使用示例
const logoGen new LogoGenerator(document.getElementById(logo-container));
logoGen.generateLogo(LOGO, {fontSize: 64,useGlow: true
});性能优化建议 SVG 优化 使用 use 复用元素压缩 SVG 代码避免不必要的精度 动画优化 使用 CSS 动画代替 SMIL使用 transform 代替位置属性避免频繁的 DOM 操作 交互优化 使用事件委托优化碰撞检测使用 requestAnimationFrame
浏览器兼容性
特性ChromeFirefoxSafariEdge基础 SVG✅✅✅✅SMIL✅✅✅✅CSS 动画✅✅✅✅滤镜✅✅✅✅
实用工具推荐 ️ SVG 编辑器 InkscapeAdobe IllustratorFigma SVG 优化工具 SVGOSVG OMGSVG Optimizer JavaScript 库 Snap.svgSVG.jsGreenSock
总结
SVG 为我们提供了强大的矢量图形能力
可缩放性 动画效果 交互能力 ️滤镜效果 如果你觉得这篇文章有帮助欢迎点赞收藏也期待在评论区看到你的想法和建议
终身学习共同成长。
咱们下一期见