如何绘制透明背景-深浅相间的方格
leaferjs 棋盘格图案
首先应该要创建两份 Frame,这样第一个 Frame 就可以设置为真正的透明背景了,然后 backgroundFrame 作为背景先添加到 app
ts
const frame = BackgroundFrame.one( {
fill: 'rgba(255,255,255,0)',
}, 0, 0, 600, 600);
const backgroundFrame = BackgroundUI.one({}, 0, 0, 600, 600);
app.tree.add(backgroundFrame); // 先添加的在底层
app.tree.add(frame); // 用于显示具体前景元素
具体代码如下:
优化-使用图片平铺的形式生成方格
ts
// #创建固定宽高的 Leafer [window]
import {
Leafer, Platform,
Rect,
registerUI,
type ILeaferCanvas,
type IRenderOptions,
type IUIInputData,
} from 'leafer-ui'
export const BackgroundUITag = 'BackgroundFrame';
const svg = Platform.toURL(
``,
'svg',
);
class BackgroundUI extends Rect {
// 2. 定义全局唯一的 tag 名称
public get __tag() {
return BackgroundUITag;
}
constructor(input: IUIInputData) {
if (!input.fill) {
input.fill = {
type: 'image',
url: svg,
mode: 'repeat',
format: 'svg',
size: { height: 100, width: 100 },
};
}
super(input);
}
// 绘制自定义内容 https://www.leaferjs.com/ui/reference/display/custom/context.html
__draw(canvas: ILeaferCanvas, options: IRenderOptions): void {
const scale = this.zoomLayer.scaleX ?? 1;
const l = 100 / scale;
// 修改第二层级的数据不会触发渲染, 例如 this.fill.size.height = 100 / scale; 不会触发渲染,所以这里需要重新赋值 fill 属性
// 修改对象 https://www.leaferjs.com/ui/guide/basic/style.html#%E4%BF%AE%E6%94%B9%E5%AF%B9%E8%B1%A1
this.fill = {
type: 'image',
url: svg,
mode: 'repeat', // 相当于 CSS 的 background-repeat: repeat
format: 'svg',
size: { height: l, width: l },
};
super.__draw(canvas, options); // 调用父类的绘制方法,确保其他样式正常渲染
}
}
registerUI()(BackgroundUI)
const leafer = new Leafer({
view: window, // view 参数支持设置 window 对象
width: 600, // 不能设置为 0, 否则会变成自动布局
height: 300,
fill: '#333'
})
leafer.add(Rect.one({ fill: '#32cd79', draggable: true }, 200, 100))
编程式生成方格
ts
import { Frame, registerUI, type ILeaferCanvas, type IRenderOptions } from 'leafer-ui';
export const BackgroundFrameTag = 'BackgroundFrame';
@registerUI()
export class BackgroundFrame extends Frame {
// 2. 定义全局唯一的 tag 名称
public get __tag() {
return BackgroundFrameTag;
}
// 绘制自定义内容 https://www.leaferjs.com/ui/reference/display/custom/context.html
__draw(canvas: ILeaferCanvas, options: IRenderOptions): void {
const { context } = canvas;
const box = this.__layout.boxBounds;
const w = box.width!;
const h = box.height!;
const scale = this.zoomLayer.scaleX ?? 1;
// 设置基础方格大小
const baseGridSize = 10;
// 根据缩放比例调整方格大小
const gridSize = baseGridSize / scale;
// 绘制透明背景的深浅方格
// 用于记录上一行的第一个方格是否为深色
let oldFirstIsDark = false;
for (let x = 0; x < w; x += gridSize) {
// 每行开始时,根据上一行的第一个方格颜色来决定当前行的第一个方格颜色
let isDark = !oldFirstIsDark;
for (let y = 0; y < h; y += gridSize) {
// 计算当前方格的宽度和高度,确保不会超出边界
const rectWidth = Math.min(gridSize, w - x);
const rectHeight = Math.min(gridSize, h - y);
// 判断当前方格的位置,决定使用深色还是浅色
context.fillStyle = isDark ? '#CCCCCC' : '#FFFFFF'; // 深色和浅色
context.fillRect(x, y, rectWidth, rectHeight);
// 切换颜色
isDark = !isDark;
}
// 更新 oldFirstIsDark 为当前行的第一个方格颜色
oldFirstIsDark = !oldFirstIsDark;
}
}
}