vue3 svg图像 的实例

1、先上个图,来自官方:

2、说明:图形包括三个组件,一个是多边形、一个圆、一个text(A,B,C,D,E,F...)。

3、图形定义:

复制代码
<svg width="200" height="200">
    <PolyGraph :stats="stats"></PolyGraph>
  </svg>

这个PolyGraph是一个自定义SFC:

复制代码
<script setup>
import AxisLabel from './AxisLabel.vue'
import { computed } from 'vue'
import { valueToPoint } from './util.js'

const props = defineProps({
  stats: Array
})

const points = computed(() => {
  const total = props.stats.length
  return props.stats
    .map((stat, i) => {
      const { x, y } = valueToPoint(stat.value, i, total)
      return `${x},${y}`
    })
    .join(' ')
})
</script>

<template>
  <g>
    <polygon :points="points"></polygon>
    <circle cx="100" cy="100" r="80"></circle>
    <axis-label
      v-for="(stat, index) in stats"
      :stat="stat"
      :index="index"
      :total="stats.length"
    >
    </axis-label>
  </g>
</template>

说明:定义一个props: stats是一个数组,points:方法是将值转为坐标,并且用' '空格连接,这个与SVG中的多边形的points是一致。

polygon:svg中显示多边形的关键词。

circle:svg中的圆,由圆心(cx,cy),及半径r组成。

axis-label:是一组text,是自定义SFC:

复制代码
<script setup>
import { computed } from 'vue'
import { valueToPoint } from './util.js'

const props = defineProps({
  stat: Object,
  index: Number,
  total: Number
})

const point = computed(() =>
  valueToPoint(+props.stat.value + 10, props.index, props.total)
)
</script>

<template>
  <text :x="point.x" :y="point.y">{{stat.label}}</text>
</template>

4、函数说明:

复制代码
export function valueToPoint(value, index, total) {
  const x = 0
  const y = -value * 0.8
  const angle = ((Math.PI * 2) / total) * index
  const cos = Math.cos(angle)
  const sin = Math.sin(angle)
  const tx = x * cos - y * sin + 100
  const ty = x * sin + y * cos + 100
  return {
    x: tx,
    y: ty
  }
}

说明:

angle:(Math.PI * 2) / total),将一个圆周,分成total分。

cos0:1

sin0:0

将value值,通过index ,来转换为对应的坐标,这个100与圆有关系,可以加以修改,这样就会平移不同的value。

5、最后官方地址:https://cn.vuejs.org/examples/#svg

可以亲自测试下,然后想一想。

相关推荐
胡gh几秒前
JS面向对象程序设计(OOP)与原型机制,到底是如何一步步走向实用的
javascript
前端缘梦3 分钟前
微信小程序登录方案实践-从账号体系到用户信息存储
前端·微信小程序
用户21411832636024 分钟前
02-N8N教程-手把手教你用 PostgreSQL 实现 N8N 数据持久化,生产环境部署实战!
前端
玄玄子5 分钟前
webpack学习指南
前端·webpack·程序员
不爱说话郭德纲7 分钟前
面试官:你给我讲讲async/await
前端·深度学习·面试
前端小巷子8 分钟前
Promise 链式调用:让异步编程更优雅
前端·面试·promise
周日不上发条9 分钟前
前端必学:CSS实现精美渐变色票据组件(含完整源码)
前端
有梦想的攻城狮15 分钟前
从0开始学vue:pnpm怎么安装
前端·javascript·vue.js
pzpcxy52017 分钟前
安装VUE客户端@vue/cli报错警告npm WARN deprecated解决方法 无法将“vue”项识别为 cmdlet、函数
前端·vue.js·npm
醉书生ꦿ℘゜এ18 分钟前
npm error Cannot read properties of null (reading ‘matches‘)
前端·npm·node.js