diff --git a/packages/vant/src/signature/Signature.tsx b/packages/vant/src/signature/Signature.tsx index b0e426316..d3a01aec2 100644 --- a/packages/vant/src/signature/Signature.tsx +++ b/packages/vant/src/signature/Signature.tsx @@ -5,7 +5,12 @@ import { defineComponent, type ExtractPropTypes, } from 'vue'; -import { createNamespace, makeNumberProp, makeStringProp } from '../utils'; +import { + inBrowser, + makeNumberProp, + makeStringProp, + createNamespace, +} from '../utils'; import { Button } from '../button'; const [name, bem, t] = createNamespace('signature'); @@ -19,6 +24,11 @@ export const signatureProps = { export type SignatureProps = ExtractPropTypes; +const hasCanvasSupport = () => { + const canvas = document.createElement('canvas'); + return !!canvas.getContext?.('2d'); +}; + export default defineComponent({ name, @@ -37,10 +47,7 @@ export default defineComponent({ isSupportTouch: 'ontouchstart' in window, }); - const hasCanvasSupport = () => { - const canvas = document.createElement('canvas'); - return !!(canvas.getContext && canvas.getContext('2d')); - }; + const isRenderCanvas = inBrowser ? hasCanvasSupport() : true; const touchMove = (event: TouchEvent) => { if (!state.ctx) { @@ -118,7 +125,7 @@ export default defineComponent({ }; onMounted(() => { - if (hasCanvasSupport()) { + if (isRenderCanvas) { state.ctx = canvasRef.value?.getContext('2d'); state.width = wrapRef.value?.offsetWidth || 0; state.height = wrapRef.value?.offsetHeight || 0; @@ -128,7 +135,7 @@ export default defineComponent({ return () => (
- {(hasCanvasSupport() && ( + {isRenderCanvas ? ( - )) ||

{props.tips}

} + ) : ( +

{props.tips}

+ )}
-

{props.tips}

diff --git a/packages/vant/src/signature/test/__snapshots__/demo.spec.ts.snap b/packages/vant/src/signature/test/__snapshots__/demo.spec.ts.snap index f7e31777b..ce57c515f 100644 --- a/packages/vant/src/signature/test/__snapshots__/demo.spec.ts.snap +++ b/packages/vant/src/signature/test/__snapshots__/demo.spec.ts.snap @@ -10,8 +10,6 @@ exports[`should render demo and match snapshot 1`] = `
+
+`; diff --git a/packages/vant/src/signature/test/index.spec.ts b/packages/vant/src/signature/test/index.spec.ts index 5530a43ce..8e66b45c1 100644 --- a/packages/vant/src/signature/test/index.spec.ts +++ b/packages/vant/src/signature/test/index.spec.ts @@ -56,3 +56,24 @@ test('submit() should output a valid canvas', async () => { expect(data.canvas).toBeNull(); expect(data.filePath).toBe(''); }); + +test('should render tips correctly', async () => { + const createElement = document.createElement.bind(document); + + const spy = jest.spyOn(document, 'createElement'); + spy.mockImplementation((tagName, options) => { + if (tagName === 'canvas') { + return {} as HTMLCanvasElement; + } + return createElement(tagName, options); + }); + + const wrapper = mount(Signature, { + props: { + tips: 'Canvas is not supported', + }, + }); + + expect(wrapper.html()).toMatchSnapshot(); + spy.mockRestore(); +});