Custom
自定义图形。
示例
使用路径自定义(推荐)
ts
import { Leafer, UI, PathCreator, PathHelper, Debug } from 'leafer-ui'
const { begin, moveTo, lineTo, close } = PathCreator
class Custom extends UI {
// 如果通过width、height无法确定图形边界,需要添加此函数计算路径边界
public __updateBoxBounds(): void {
PathHelper.toBounds(this.__.path, this.__layout.boxBounds)
}
public __updatePath() {
const { width, height } = this.__
const rx = width / 2, ry = height / 2
begin(this.__.path = [])
moveTo(rx, 0)
lineTo(rx, ry)
lineTo(0, ry)
close()
}
}
Debug.enable = true
Debug.showRepaint = true // 通过显示重绘区域,查看图形边界是否准确
const leafer = new Leafer({ view: window })
const custom = new Custom({ x: 100, y: 100, width: 200, height: 50, fill: 'blue', draggable: true })
leafer.add(custom)
使用 canvas.context 自定义
需要自己处理盒子模型、样式、碰撞检测。
ts
import { Leafer, UI } from 'leafer-ui'
import { ILeaferCanvas, IRadiusPointData } from '@leafer-ui/interface'
class Custom extends UI {
// 如果通过width、height无法确定图形边界,需要重写此函数
__updateBoxBounds(): void {
const box = this.__layout.boxBounds
const { width, height } = this.__
box.x = 0
box.y = 0
box.width = width
box.height = height
}
// 绘制碰撞路径, 根据 this.__layout.hitCanvasChanged 自动调用此函数更新
__drawHitPath(hitCanvas: ILeaferCanvas): void {
const { context } = hitCanvas
const { width, height } = this.__
context.beginPath()
context.rect(0, 0, width, height)
}
// 碰撞检测
__hit(inner: IRadiusPointData): boolean {
const { context } = this.__hitCanvas
if (context.isPointInPath(inner.x, inner.y)) return true
// 碰撞半径
const lineWidth = inner.radiusX * 2 // 可增加自定的线宽
if (context.lineWidth !== lineWidth) {
context.lineWidth = lineWidth
context.stroke()
}
return context.isPointInStroke(inner.x, inner.y)
}
// 绘制自定义内容
__draw(canvas: ILeaferCanvas): void {
const { context } = canvas
const { width, height } = this.__
context.fillStyle = 'blue'
context.fillRect(0, 0, width / 2, height)
context.strokeStyle = 'blue'
context.strokeRect(width / 2, 0.5, width / 2, height - 1)
}
}
const leafer = new Leafer({ view: window })
const custom = new Custom({ x: 100, y: 100, width: 200, height: 50, draggable: true })
leafer.add(custom)