教你如何用 CSS Painting API 画新小米logo, border-radius可是画不出的

冰霜 -
教你如何用 CSS Painting API 画新小米logo, border-radius可是画不出的

logo-mi2.png
这是小米的新logo
用border-radius可是画不出来的
因为这个图的圆是[超椭圆]
border-radius 能写出超椭圆吗?

什么是超椭圆

超椭圆(superellipse)也称为Lamé曲线,是一种类似于椭圆的封闭曲线,保留了椭圆的长轴、短轴、对称性的特点。
image.png

怎么做到

使用 CSS Painting API
用这个玩意可以利用js直接绘制元素的背景、边框或内容。

现在开始
写一个javascript文件 huizhi.js
代码内容如下

const Print_demo = class {
    paint(ctx, size) {
        ctx.fillStyle = 'green'

        const n = 4

        let m = n

        const r = size.width / 2
        const w = size.width / 2
        const h = size.height / 2

        ctx.beginPath();

        for (let i = 0; i < (2 * r + 1); i++) {
            const x = (i - r) + w
            const y = (Math.pow(Math.abs(Math.pow(r, m) - Math.pow(Math.abs(i - r), m)), 1 / m)) + h

            if (i == 0)
                ctx.moveTo(x, y)
            else
                ctx.lineTo(x, y)
        }

        for (let i = (2 * r); i < (4 * r + 1); i++) {
            const x = (3 * r - i) + w
            const y = (-Math.pow(Math.abs(Math.pow(r, m) - Math.pow(Math.abs(3 * r - i), m)), 1 / m)) + h
            ctx.lineTo(x, y)
        }

        ctx.closePath()
        ctx.fill()
    }
}


registerPaint('hua', Print_demo);

看上面代码内容, 定义了个Print_demo 类,这个里面是画超椭圆的方法,里面的方法就是
image.png这个公式的实现, 在canvas 上可以画出这个形状,但是这个api里面的ctx和canvas 元素的上下文对象ctx是不一样的,这里就不说了.
然后 用 registerPaint这个方法注册 Print_demo,名个名字叫hua

如何使用

1.引入这段js
2.调用 CSS.paintWorklet.addModule('./huizhi.js');
3.在css文件里面 background:paint(hua)

好了 ,就是这个形状,超椭圆,需要调一下上面的参数n,可以和小米的差不多一样

image.png

有了这个玩意,你可以为所欲为的写各种图案
特别申明:本文内容来源网络,版权归原作者所有,如有侵权请立即与我们联系(cy198701067573@163.com),我们将及时处理。
下一篇: HTML学习笔记

Tags 标签

css3javascripthtml5前端css

扩展阅读

加个好友,技术交流

1628738909466805.jpg