CSS Houdini 快速入门(2)—paint API

582 阅读1分钟
  1. 小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。

主要通过一个自定义下划线的例子帮助大家理解如何使用 houdini 的 Paint API。

准备工作

创建文件夹作为项目目录

文件名说明
index.htmlhtml 文件
index.js
style.css
custombg.js

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <title>Document</title>
</head>
<body>
    <h1>Hello Houdini</h1>
    <script src="index.js"></script>
</body>
</html>

custombg.js

class CustomBg{
    paint(ctx,size,props){
        console.log(size)
    }
}
registerPaint('custombg',CustomBg)
  • 创建一个类 CustomBg 其中实现一个 paint 方法,该方法接收 3 个参数分别为上下文(context),尺寸(size) 和属性(properties)
  • 然后用 registerPaint 对该自定义

index.js

CSS.paintWorklet.addModule('custombg.js')
  • 需要 index.js 文件中添加一下这个模块,

style.css

body{
    margin: 0;
    height: 100vh;
    padding: 3em;
}

h1{
    font-size: 3em;
    margin-top: 3em;
    padding: .2em;
    background-image: paint(custombg);
}
  • 在 style.css 文件中,调用一下 custombg 自定义绘制样式,需要paint(custombd)作为 h1 背景图应用 h1 元素上。
PaintSize {width: 417, height: 86}

可以输出元素的尺寸,也可以查看其他两个参数上下文(context)和属性(properties)

class CustomBg{
    paint(ctx,size,props){
        ctx.beginPath();
        ctx.fillStyle = 'orangered';
        ctx.arc(20,20,8,0,2 * Math.PI);
        ctx.fill();
    }
}

registerPaint('custombg',CustomBg)

houdini_paint_001.png

class CustomBg{
    paint(ctx,size,props){

        for (let i = 0; i < 6; i++) {
            
            ctx.beginPath();
            ctx.fillStyle = 'orangered';
            ctx.arc(20 * (i + 1) ,20,8,0,2 * Math.PI);
            ctx.fill();
        }
    }
}

houdini_paint_002.png

class CustomBg{
    paint(ctx,size,props){

        for (let i = 0; i < 6; i++) {
            
            ctx.beginPath();
            ctx.fillStyle = 'orangered';
            ctx.arc(20 * (i + 1) ,size.height - 10,8,0,2 * Math.PI);
            ctx.fill();
        }
    }
}

registerPaint('custombg',CustomBg)

我们再将效果做的稍微复杂一些,上面通过一个 for 绘制多个点,然后利用传入的元素高度数据,来确定绘制点的位置。

houdini_paint_003.png