This article is written by BingLee1994, a member of the team, and we have authorized the exclusive use of doodle big front, including but not limited to editing, original annotation and other rights.
Do you get the feeling that you’re just happy to be able to draw with a few lines of CSS without having to hunt around for SVG or upload an image? Gradients can do a lot of things like patterns, masks, common shapes, etc.
We’re familiar with linear gradients and tapered gradients, so here’s another friend, Conic-gradient.
compatibility
All major modern browsers are compatible.
All the fun and efficient CSS features are not compatible with IE11, so don’t let it stand in the way of progress.
Noun explanation
If you’re new to gradients, a quick note: Gradients consist of orientation, position, and multiple color stops.
Color the stationary point
A color stagnation point consists of a color and a position, separated by a space, as shown in the following picture:It can be seen that the background changes from green → red → blue, and the circles controlling the color are the color stagnation point. In this figure, green and blue are at the head and tail respectively, and red is at 25%, so the red stagnation point can be expressed as:red 25%
, in the head and tail can not write position.
Direction and Center
In the image above we can clearly see that the gradient is to the right, so we can specify the gradient at any Angle, as shown belowIn particular, taper and radial gradients can also specify the center point, radial gradients can also specify the radius, prototype ellipse, and so on.
conic-gradient
Ok, so what is conic-gradient? As the name suggests, look at the picture belowDo you see that? The color goes around the center pointI rotate around, just like a cone, this is a tapered gradient. The stagnation point of the color is shown in the red line below, just on the radius line:
grammar
Backgrouns-image: conic-gradient([Angle [at position]], color stagnation point 1, color stagnation point 2, color stagnation point… The parentheses indicate non-essential attributes. The default Angle is 0 and the position is right in the center of the element. The color stagnation position can be expressed in an Angle notation in addition to percentages.
Give it a try
The syntax looks a bit long, so don’t be afraid. Let’s write a CSS to try it out:
div {
width: 200px;
height: 200px;
background-image: conic-gradient(orange, blue 50%, purple)
}
Copy the code
Render as follows: Make a circle around the center, starting from orange to 50% blue, then from blue to 360° purple, it’s that simple!
Then the above 50% can also be expressed as an Angle: Conic-gradient (Orange, Blue 180DEg, Purple), in particular, two angles can be specified to indicate the Angle area covered by the color, For example, Conic-gradient (Orange, Blue 180DEg 240DEg, Purple).
Start drawing pie charts
How can it be understood without practical application? In this article, we take a common pie chart application case to further experience the taper gradient.
Below: The orange area accounts for 30%.
What’s the difference?
What’s the difference between our gradient and this pie chart?
That’s right. Did you see that? The interface between the pie background and the orange scalloped area (hereafter referred to as progress) is hard rather than gradual.So how do we do that? Don’t worry, let’s draw the gradient first:
div {
width: 200px;
height: 200px;
background-image: conic-gradient(orange, purple 30%)}Copy the code
Let the color interface harden
Oh ~, surprise, we found that in starting at 0 ° and 360 °, is a direct to purple orange hard line, rather than the gradient, because = 0 ° 360 °, the same Angle position in two colors, then the two color distance is zero, in other words, to orange gradient to purple space length is 0, the nature is no gradient on the vision, The connector hardens and changes color directly.
With this in mind, we can easily draw the pie chart above by adding two color stops to the above 30% of the positions, so that the two transition directly.
Let’s modify the CSS code as follows:
div {
width: 200px;
height: 200px;
background-image: conic-gradient(orange 30%, purple 30%);
/* Set two stagnation points orange and purple at 30% of the position, then the hard transition at this position without gradient */
}
Copy the code
And you’re done. Don’t forget to add oneborder-radius
, so easy!
The pie chart moves
This is an interesting thing that we definitely need to package into components to use in the real world. Above we easily drew a pie chart of 30%. Similarly, by changing the percentage, we can make the pie chart move.
You can just copy the FOLLOWING HTML code for this exercise
<body>
<style>
body {
height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
#pie-chart {
width: 200px;
height: 200px;
border-radius: 100px;
background-image: conic-gradient(orange 0%, purple 0%);
margin-bottom: 24px;
}
</style>
<div id="pie-chart"></div>
<input
id="slider"
type="range"
value="0"
max="100"
min="0"
step="10"
/>
<script type="text/javascript">
// Write the js code here
</script>
</body>
Copy the code
Add slider events
In this example, the value of the slider ranges from 0 to 100, corresponding to the position of the color stagnation point. The percentage of the pie chart can be controlled by adding the input event of the slider:
<script type="text/javascript">
const elPieChart = document.getElementById('pie-chart')
const elSlider = document.getElementById('slider')
elSlider.oninput = function updateChart() {
const { value } = elSlider
// Convert slider value to stagnation position
elPieChart.style.backgroundImage = `conic-gradient(orange ${value}%, purple ${value}%) `
}
</script>
Copy the code
You see, is so short a few lines of code, the pie chart can move up 😊!
Customizable components
We define two variables, a background color and a progress color, and then modify the CSS background:
<script type="text/javascript">
// Custom colors
const chartColor = '#C6E9FF'
const chartProgressColor = '#4589EF'
const elPieChart = document.getElementById('pie-chart')
const elSlider = document.getElementById('slider')
// Set the color for the first rendering
elPieChart.style.backgroundImage = `conic-gradient(${chartProgressColor} 0%, ${chartColor}0%) `
elSlider.oninput = function updateChart() {
const { value } = elSlider
// Change the pie chart progress
elPieChart.style.backgroundImage = `conic-gradient(${chartProgressColor} ${value}%, ${chartColor} ${value}%) `
}
</script>
Copy the code
Continue to optimize
You think this is the end of it? Let’s go back to the code, just add a color requirement, and the JS code starts getting really ugly, Mainly in elPieChart. Style. The backgroundImage = ` conic – gradient (${chartProgressColor} ${100} value * %, ${chartColor} ${value * 100}%)
This blob of code is very irritating because:
- this
css
The string is very long. - in
js
Joining togethercss
Strings have no code hints, so it’s very easy to make mistakes, missing punctuation Spaces and so on. Debugging is disgusting. - Today I write, I can understand, a few days LATER I will see, I can not understand, no maintenance!
The good news is that this is a typical application scenario using CSS variables, tutorial portal, if you encounter similar annoyance in your daily component development.
Code maintainability is an important part of the overall project, and should not be overlooked in order to catch up or be lazy.
Use CSS variables to slim down
Now, let’s leave everything style-related in the CSS code, in this case two colors and a pie chart progression, and expose the corresponding CSS variables for JS to manipulate accordingly. Yes, CSS code should stay in CSS.
Modify the above CSS code as follows to define the variables that need to be exposed to js and give them initial values:
#pie-chart {
/* Declare variables and initialize */
--chartColor: orange; /* Background color */
--chartProgressColor: purple; /* Progress color */
--chartProgress: 0%; / * * / progress
width: 200px;
height: 200px;
border-radius: 100px;
/* 使用变量,(有点模板的意思) */
background-image: conic-gradient(
var(--chartProgressColor) var(--chartProgress),
var(--chartColor) var(--chartProgress)
);
margin-bottom: 24px;
}
Copy the code
Then directly manipulate CSS variables in JS, API portal
<script type="text/javascript">
// Custom colors
const chartColor = '#C6E9FF'
const chartProgressColor = '#4589EF'
const elPieChart = document.getElementById('pie-chart')
const { style } = elPieChart
const elSlider = document.getElementById('slider')
// Set the color for the first rendering
style.setProperty('--chartColor', chartColor)
style.setProperty('--chartProgressColor', chartProgressColor)
elSlider.oninput = function updateChart() {
const { value } = elSlider
// Change the pie chart progress
style.setProperty('--chartColor', chartColor)
style.setProperty('--chartProgressColor', chartProgressColor)
style.setProperty('--chartProgress'.`${value}% `)}</script>
Copy the code
We’ve now replaced the traditional CSS concatenation string with a better, more readable variable, and optimized the JS code to be more JS.
You can continue the refactoring however you like, so the CSS variable part of the above manipulation can actually be optimized, you can write utility classes, but anyway, CSS is finally out of the way.
Imagine, if our component DOM level is very deep, but also according to the old stupid method, layer by layer to find nodes, style penetration, will be a nightmare, using CSS variables, just focus on the variable itself, without considering the DOM level, and developers can better maintenance, but also convenient for users through the means of CSS hack to customize the style, Hopefully you get to this point.
More scenes
In addition to pie charts, circular progress bars, Loading animations, masks, etc., tapered gradients are also used in scenarios, so let your imagination run wild.
Like this article remember to triple support 😙