paint api 在表格单元格中不生效,因表格式渲染上下文会忽略 background-image: paint(...);须确保单元格有明确尺寸、禁用 border-collapse: collapse、设 padding: 0 或手动偏移坐标,并通过 css 自定义属性传参,worklet 中禁止访问 dom 且需加 try/catch 防静默失败。

Paint API 在表格单元格中不生效?先确认渲染上下文
直接对 <td> 或 <code><th> 设置 <code>background-image: paint(...) 大概率没反应——因为 Paint API 的自定义画布默认不作用于「表格式渲染上下文」中的单元格。浏览器在 table 布局阶段会合并、裁剪或跳过部分背景绘制,尤其是当单元格没有显式设定 background-color 或 background-image 时,paint() 可能被完全忽略。
必须确保:单元格有明确的尺寸(width/height 或 min-width/min-height),且未被 table-layout: auto 动态挤压到 0;同时要避免父级 <table> 或 <code><tbody> 设置了 <code>background 覆盖子元素。
-
table { table-layout: fixed; }更可控,配合列宽col { width: 120px; } - 每个
<td> 至少设 <code>min-width: 1px; min-height: 1em;(哪怕内容为空) - 禁用
border-collapse: collapse下的隐式重叠干扰(可临时改用separate验证)
注册 worklet 并编写 cell-pattern.js 时注意 scope 隔离
CSS Paint API 的 worklet 脚本运行在独立线程,无法访问 DOM、window 或全局变量。常见错误是直接在 paint() 里调用 document.querySelector 想读取单元格数据——这会静默失败,控制台只报 TypeError: Illegal invocation。
所有参数必须通过 CSS 自定义属性传入,例如:
td.patterned {
--pattern-type: "dots";
--pattern-color: #3b82f6;
background-image: paint(cellPattern);
}
worklet 中只能读 args 和 properties:
registerPaint('cellPattern', class {
static get inputProperties() {
return ['--pattern-type', '--pattern-color'];
}
paint(ctx, size, props) {
const type = props.get('--pattern-type').toString();
const color = props.get('--pattern-color').toString();
// ✅ 此处绘图
}
});
- 不要在 worklet 里 import 外部模块(ESM 不支持),所有逻辑写在一个文件内
-
props.get()返回CSSUnitValue或CSSKeywordValue,字符串需调用.toString() - 若需不同图案类型,用
switch(type)分支,别试图动态import()
用 ctx 绘制时,坐标原点与单元格边界强相关
Paint API 的 ctx 坐标系原点就是当前单元格左上角(含 padding),size 是 content box 尺寸(不含 padding/border)。但表格单元格的 padding 默认不为 0,而 paint() 不自动避开 padding 区域——你画的图案会从左上角开始铺满整个 content box,可能被 padding “遮掉一部分”。
典型表现:右下角图案缺失、水平/垂直偏移感明显。
- 统一设置
td { padding: 0; }再调试图案定位 - 若需保留 padding,用
ctx.translate(leftPad, topPad)手动偏移,再基于size.width - leftPad - rightPad计算绘图范围 - 避免用
ctx.fillRect(0,0,size.width,size.height)全填色——它会压住 border,应优先用ctx.clip()约束到 content 区域
性能敏感:避免在每个单元格重复计算复杂图案
一个 50×30 的表格就有 1500 个单元格,如果每个 paint() 都做路径生成、渐变创建或循环点阵,帧率会骤降。Chrome DevTools 的 Rendering 面板里能看到大量 Paint 事件堆积。
优化关键:把耗时操作提到 worklet 初始化阶段,复用对象。
- 在
class外层预建const dotGradient = new CanvasGradient(...)(但注意:CanvasGradient 不能跨 paint 调用复用,需每次新建) - 对固定尺寸的图案(如 4×4 像素点阵),用
ctx.createPattern()生成一次CanvasPattern,然后在paint()里ctx.fillStyle = pattern; ctx.fillRect(...) - 用
ctx.setTransform(1,0,0,1,0,0)重置变换矩阵,防止上一个单元格的scale或rotate污染下一个
最易被忽略的是:没有给 registerPaint 加 try/catch,worklet 报错会导致整张表背景失效且无提示——务必在 paint 方法入口加 try {...} catch(e) { console.warn('paint failed:', e); }。
大量免费API接口:立即使用
涵盖生活服务API、金融科技API、企业工商API、等相关的API接口服务。免费API接口可安全、合规地连接上下游,为数据API应用能力赋能!











