svg学习

版权声明:本人原创,码字辛苦,整理代码更是辛苦,转发请说明原处https://blog.csdn.net/qq_37815596谢谢! https://blog.csdn.net/qq_37815596/article/details/88657522

学习SVG主要用来解决,图片和文字、小图标等,在不同分辨率屏幕下,位置会移动。

  • 注意点

1.svg标签内不能使用div等html标签,但是可以用g来代替,见链接:https://developer.mozilla.org/en-US/docs/Web/SVG/Element/g

2.svg宽高固定时,下面的其他图片位置不会因为屏幕分辨率而变动

3.svg 的文本:

<text x="20" y="35" class="small">My</text>

4.使用<img>元素来嵌入SVG图像

5.缩放,实现适配,将宽高写在viewBox内,然后设置width和height为100%

<svg width="100%" height="100%" preserveAspectRatio="xMidYMid meet" viewBox="0 0 380 360" ><svg />

6.获取当前页面绘制的svg图像的url,参考链接:https://stacktrace.tech/2016-08-17/convert-svg-to-png-and-save/

componentDidMount(){
    var svg = document.getElementById("svg_o");
    // get svg source.
    var serializer = new XMLSerializer();
    var source = serializer.serializeToString(svg);
    // add name spaces.
    if(!source.match(/^<svg[^>]+xmlns="http\:\/\/www\.w3\.org\/2000\/svg"/)){
        source = source.replace(/^<svg/, '<svg xmlns="http://www.w3.org/2000/svg"');
    }
    if(!source.match(/^<svg[^>]+"http\:\/\/www\.w3\.org\/1999\/xlink"/)){
        source = source.replace(/^<svg/, '<svg xmlns:xlink="http://www.w3.org/1999/xlink"');
    }
    // add xml declaration
    source = '<?xml version="1.0" standalone="no"?>\r\n' + source;
    //convert svg source to URI data scheme.
    var url = "data:image/svg+xml;charset=utf-8," + encodeURIComponent(source);
    //set url value to a element's href attribute.
    document.write('<img src="' + url + '"/>');
  }
  • demo

App.js

import React, { Component } from 'react';
import "./App.css"
import LeftFoot from "./[email protected]"
import RightFoot from "./[email protected]"
import purple from "./[email protected]"
class App extends Component {
  render() {
    return (
      <div>
        <svg width="300" height="180">
          <image xlinkHref={LeftFoot} x="100" y="0" height="100%" width="100%"/>
          <image xlinkHref={RightFoot} x="0" y="0" height="100%" width="100%"/>
          <image xlinkHref={purple} x="160" y="10" height="20px" width="20px"/>
          {/* cx 和 cy 属性定义圆点的 x 和 y 坐标。如果省略 cx 和 cy,圆的中心会被设置为 (0, 0),r 属性定义圆的半径。 */}
          <circle cx="140"  cy="58" r="10" />
          <circle cx="164"  cy="54" r="10" className="red" />
          <circle cx="260" cy="70" r="10" className="fancy" />
          <rect id="R" width="100%" x="0" y="0" height="1" fill="green"/>
        </svg>
      </div>
    );
  }
}
export default App;

App.css

.red {
  fill: red;
}

.fancy {
  fill: none;
  stroke: yellow;
  stroke-width: 3pt;
}
扫描二维码关注公众号,回复: 6238075 查看本文章

猜你喜欢

转载自blog.csdn.net/qq_37815596/article/details/88657522
SVG