Creating UI Components in SVG
SVG empowers web interface construction: Exploring the infinite possibilities of custom UI components
SVG shows great potential in web interface construction. It may be a bit difficult to learn SVG, but its original intention is to create shapes, while supporting elements such as text, links and ARIA tags. Although CSS can also achieve some of the same effects, CSS is more difficult in precise positioning, especially cross-windows and responsive development.
What is unique about SVG is that its positioning is based on a coordinate system, similar to the game "battleship". This means that determining the location of elements, how they are drawn, and relative positions between elements are very intuitive. CSS positioning is mainly used for layout, which is good because the elements in the document stream correspond to each other. But if you want to create specific components with overlapping and precise placement of elements, this feature actually increases the difficulty.
Once you master SVG, you can draw any graphics and make it scaleable on any device. Even this website uses SVG to create custom UI elements, such as the avatar (metadata!).
This article will not cover the entire content of SVG (you can learn some basics here, here, here, and here), but to illustrate the possibilities SVG brings to UI component development, let's discuss a specific use case and break down the idea of building custom components.
Timeline Task List Component
Recently, I worked on a project with the Netlify team. We need to show viewers where they are currently watching videos in the course video series. In other words, we need to create something like a to-do list, but show overall progress when the project is finished. (We created a free space-themed learning platform, which is very cool. Yes, I used the word "very cool".)
The effects are as follows:
How should we achieve it? I'll show the Vue and React examples separately so you can understand how it is implemented in both frameworks.
Vue version
We decided to build the platform using Next.js (to try out our own Netlify Next build plugin), but I am more familiar with Vue, so I wrote the initial prototype in Vue and then ported to React.
Complete CodePen demo: [CodePen link should be inserted here]
Let's analyze the code step by step. First, this is a single file component (SFC), so template HTML, reactive scripts, and scope styles are all encapsulated in one file.
We store some virtual tasks in data, including whether each task has been completed. We will also create a method that can be called on the click command to switch states.
export default { data() { return { tasks: [ { name: 'thing', done: false }, // ... ] }; }, methods: { selectThis(index) { this.tasks[index].done = !this.tasks[index].done } } };
Now, we want to create an SVG with a flexibly adjusting viewBox according to the number of elements. We also need to tell the screen reader that this is a demo element and we will provide the title with the unique ID "timeline". (Get more information on creating accessible SVGs.)
<template> <div> <div> <svg :viewbox="`0 0 30 ${tasks.length * 50}`" aria-labelledby="timeline" fill="white" role="presentation" stroke="currentColor" width="30" xmlns="http://www.w3.org/2000/svg"> <title>timeline element</title> </svg> </div> </div> </template>
stroke is set to currentColor for flexibility - if you want to reuse the component in multiple locations, it will inherit the colors used by the encapsulated div.
Next, inside the SVG, we want to create a vertical line with the same length as the task list. The lines are very simple. We have x1 and x2 values (the line draws on the x-axis), and similarly, y1 and y2.
<line :y1="num2" :y2="tasks.length * num1 - num2" x1="10" x2="10"></line>
The x-axis always stays at 10 because we are drawing lines from top to bottom, not from left to right. We store two numbers in data: the spacing we want, i.e. num1, and the margin we want, i.e. num2.
data() { return { num1: 32, num2: 15, // ... } }
The y-axis starts with num2, subtracting the margin from the end. tasks.length multiplied by the spacing num1.
Now, we need a circle on the line. Each circle indicates whether the task has been completed. Each task requires a circle, so we will use v-for and the unique key, i.e. index (it is safe to use here because they will never be reordered). We connect the click directive to our method and pass the index as a parameter.
Circles in SVG are composed of three properties. The center of the circle is located in cx and cy, and we then draw the radius with r. Like lines, cx starts at 10. The radius is 4 because it is readable at this scale. cy will be spaced like a line: index times spacing (num1), plus margins (num2).
Finally, we will set the padding using the ternary operator. If the task has been completed, populate the currentColor. If not, fill in white (or any background color). For example, this could be used to use a prop fill that passes the background, which contains light and dark circles.
<circle :cy="i * num1 num2" :fill="task.done ? 'currentColor' : 'white'" :key="task.name" cx="10" r="4" v-for="(task, i) in tasks"></circle>
Finally, we use a CSS grid to align divs containing the task name. The layout is roughly the same, we iterate through the task and bind it to the same click event to switch the completed state.
<template> <div> <div :key="task.name" v-for="(task, i) in tasks"> {{ task.name }} </div> </div> </template>
React version
This is the final result of the React version. We are working on opening source so that you can view the full code and its history. Here are some modifications:
- We use CSS module instead of SFC in Vue
- We import Next.js links, so instead of switching the "completed" state, we take the user to a dynamic page in Next.js
- The tasks we use are actually the stages of the course—or what we call “tasks”—where they are passed in, not held by components.
Most other functions are the same :)
// React code snippet (the complete React code should be pasted here)
Final version
You can view the final running version here: [The final version link should be inserted here]
The component is flexible enough to accommodate lists of different sizes, multiple browsers, and responsive resizing. It also enables users to better understand their progress in the course.
But this is just a component. You can create as many UI elements as you like: knobs, controls, progress indicators, loaders...the possibilities are endless. You can style it with CSS or inline styles, you can update it based on prop, context or reactive data, with endless possibilities! I hope this opens up some ideas on how to develop more engaging Web UI elements.
The above is the detailed content of Creating UI Components in SVG. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

It's out! Congrats to the Vue team for getting it done, I know it was a massive effort and a long time coming. All new docs, as well.

I had someone write in with this very legit question. Lea just blogged about how you can get valid CSS properties themselves from the browser. That's like this.

I'd say "website" fits better than "mobile app" but I like this framing from Max Lynch:

The other day, I spotted this particularly lovely bit from Corey Ginnivan’s website where a collection of cards stack on top of one another as you scroll.

If we need to show documentation to the user directly in the WordPress editor, what is the best way to do it?

There are a number of these desktop apps where the goal is showing your site at different dimensions all at the same time. So you can, for example, be writing

CSS Grid is a collection of properties designed to make layout easier than it’s ever been. Like anything, there's a bit of a learning curve, but Grid is

I see Google Fonts rolled out a new design (Tweet). Compared to the last big redesign, this feels much more iterative. I can barely tell the difference
