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

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

相关推荐
凤山老林1 小时前
从美团全栈化看 AI 冲击:前端转全栈,是自救还是必然
前端·人工智能·状态模式
777VG8 小时前
PostgreSQL +martin将多张表输出成一个 MVT
前端·数据库·postgresql
mayaairi9 小时前
JS循环语句深度解析:嵌套for、while与do...while
开发语言·前端·javascript
To_OC9 小时前
啃完流式输出:从一个卡顿的 LLM 接口开始,我搞懂了数据流到底怎么 “流”
前端·javascript·llm
阳光是sunny9 小时前
LangGraph实战教程:defer延迟节点——让收尾工作自动排到最后
前端·人工智能·后端
kyriewen10 小时前
我用了三周Claude Code Skills——总结出5条铁律,第3条最反直觉
前端·ai编程·claude
阳光是sunny10 小时前
LangGraph实战教程:控制流详解
前端·人工智能·后端
格尔曼Noah11 小时前
Safari浏览器中如何只允许指定网站下载
前端·safari
用户0595401744611 小时前
用了3年Redis,才发现我一直没搞懂缓存一致性测试
前端·css
swipe11 小时前
07|(前端转后全栈)为什么后端也要缓存?从前端缓存思维理解 Redis
前端·后端·全栈