SVG has been widely used in recent years due to various advantages. Unfortunately, so far, wechat applet does not support using SVG in the form of XML, which greatly reduces the flexibility of SVG. Most people choose to give up using SVG icon scheme in wechat applet.
So, is there really no way to use SVG ICONS happily in wechat applets? Let’s first examine the requirements for using SVG ICONS:
- Be able to introduce use
- Be able to adjust colors
First of all, there is no problem with the first point. Wechat applet supports the introduction of SVG in the form of image.src. Now comes the focus of this article, how to make image-formatted SVG color-changing.
In my recent study of CSS, I found that there is an attribute that can make the opaque part of the DOM cast a shadow. This attribute is drop-shadow, and the value of the attribute is roughly similar to that of box-shadow. Using this property, we can cast a color-changing shadow on an SVG image, and then we can hide the original part to achieve a color-changing SVG icon.
Let’s start by creating a DOM structure:
<view class="svg_icon">
<image class="svg_icon-inner" src="/path/icon.svg"/>
</view>
Copy the code
Next add CSS:
.svg_icon {
display: inline-flex;
width: 1em;
height: 1em;
overflow: hidden;
}
.svg_icon-inner {
width: 1em;
height: 1em;
transform: translateY(-1em);
filter: drop-shadow(0 1em 0 currentColor);
}
Copy the code
Let me explain why WE set up the DOM structure and CSS this way: First, svg_icon is the container for the entire icon, responsible for setting the size of the icon (1em= font size of the parent container) and hiding the excess (i.e. the original part of the icon), while svg_icon-inner is responsible for rendering SVG and casting colored shadows. The need to change the COLOR of SVG can be achieved by giving svG_icon-inner the same width and height as the parent container and setting it to an offset in the opposite direction of the projection (setting the projection color to currentColor will cause the icon color to change with the font color of the parent container).
There is a disadvantage in this scheme. If there is a transform animation in the page and it is triggered, the icon will blink. I am not sure about the specific reason.