alipay-emulator/uni_modules/lime-barcode/components/l-barcode/useCanvas.ts

117 lines
2.9 KiB
TypeScript

// @ts-nocheck
// #ifndef UNI-APP-X
import { shallowReactive, onMounted } from '@/uni_modules/lime-shared/vue';
import { getRect } from '@/uni_modules/lime-shared/getRect';
// #endif
import { canIUseCanvas2d } from '@/uni_modules/lime-shared/canIUseCanvas2d'
import { createImage } from '@/uni_modules/lime-shared/createImage'
import type { CanvasState } from './type'
// #ifndef APP-ANDROID || APP-IOS
type Method = (...args : any[]) => any;
interface Obj {
[key : string] : any;
}
function createProxy(canvas : UniCanvasElement, node : UniCanvasElement) : Obj {
const proxy = new Proxy({}, {
get(target : UniCanvasElement, key : string) : any {
if (typeof node[key] === 'function') {
return (...args : any[]) => {
return (node[key] as Method)(...args);
};
}
return node[key];
},
set(target : UniCanvasElement, key : string, value : any) : boolean {
node[key] = value;
canvas[key] = value
return true;
},
});
return proxy;
}
// #endif
// #ifndef UNI-APP-X
export function useCanvas(selector : string, component : ComponentPublicInstance) {
const isCanvas2d = canIUseCanvas2d()
const canvas = shallowReactive<CanvasState>({
width: 300,
height: 150,
node: null as UniCanvasElement | null,
_node: null,
init: false
})
onMounted(() => {
getRect(selector, component, isCanvas2d).then(({ width, height, node }) => {
canvas.width = width
canvas.height = height
if (node) {
// WechatMiniprogram.NodesRef
canvas.node = createProxy(canvas, node) // as WechatMiniprogram.Canvas
canvas._node = node
} else {
const ctx = uni.createCanvasContext(selector.replace('#', ''), component);
const node = shallowReactive({
getContext: (type : string) => {
if (type == '2d') {
return ctx
}
},
createImage,
width: 300,
height: 150
})
canvas.node = createProxy(canvas, node)
}
canvas.init = true
})
})
return canvas
}
// #endif
// #ifdef UNI-APP-X
export function useCanvas(selector : string, component : ComponentPublicInstance) {
const isCanvas2d = canIUseCanvas2d()
const canvas = shallowReactive<CanvasState>({
width: 300,
height: 150,
node: null,
_node: null,
init: false
})
// 异步调用方式, 跨平台写法
uni.createCanvasContextAsync({
id: selector,
component,
success: (context : CanvasContext) => {
const canvasContext = context.getContext('2d')!;
const node = canvasContext.canvas;
console.log('isCanvas2d', isCanvas2d)
if (isCanvas2d) {
canvas._node = node
// @ts-ignore
canvas.node = createProxy(canvas, node)
} else {
const canvasContext = context.getContext('2d')!;
const node = shallowReactive({
getContext: (type : string) => {
if (type == '2d') {
return canvasContext
}
},
createImage,
width: 300,
height: 150
})
canvas.node = createProxy(canvas, node)
}
canvas.init = true
}
})
return canvas
}
// #endif