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

这是小米的新logo
用border-radius可是画不出来的
因为这个图的圆是[超椭圆]
border-radius 能写出超椭圆吗?
什么是超椭圆
超椭圆(superellipse)也称为Lamé曲线,是一种类似于椭圆的封闭曲线,保留了椭圆的长轴、短轴、对称性的特点。
怎么做到
使用 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 类,这个里面是画超椭圆的方法,里面的方法就是
这个公式的实现, 在canvas 上可以画出这个形状,但是这个api里面的ctx和canvas 元素的上下文对象ctx是不一样的,这里就不说了.
然后 用 registerPaint这个方法注册 Print_demo,名个名字叫hua
如何使用
1.引入这段js
2.调用 CSS.paintWorklet.addModule('./huizhi.js');
3.在css文件里面 background:paint(hua)
好了 ,就是这个形状,超椭圆,需要调一下上面的参数n,可以和小米的差不多一样

评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论