diff --git a/src/graphic/helper/image.ts b/src/graphic/helper/image.ts index 858964056..81948e10f 100644 --- a/src/graphic/helper/image.ts +++ b/src/graphic/helper/image.ts @@ -62,7 +62,12 @@ export function createOrUpdateImage( if (cachedImgObj) { image = cachedImgObj.image; - !isImageReady(image) && cachedImgObj.pending.push(pendingWrap); + if (isImageReady(image)) { + onload && onload(image, cbPayload); + } + else { + cachedImgObj.pending.push(pendingWrap); + } } else { image = platformApi.loadImage( diff --git a/test/ut/spec/graphic/Image.test.ts b/test/ut/spec/graphic/Image.test.ts index c3c3d2f72..8b483f9cc 100644 --- a/test/ut/spec/graphic/Image.test.ts +++ b/test/ut/spec/graphic/Image.test.ts @@ -1,12 +1,29 @@ +import {createOrUpdateImage} from '../../../../src/graphic/helper/image'; import {Image as ZRImage} from '../zrender'; class HTMLImageElement { width: number height: number + src?: string constructor() {} } +class Image { + width?: number + height?: number + onload?: () => void + + constructor(width?: number, height?: number, onload?: () => void) { + this.width = width || 1; + this.height = height || 1; + this.onload = onload; + setTimeout(() => { + this.onload?.(); + }, 100); + } +} + describe('Image', function () { it('Should get width and height from style by default', function () { @@ -62,4 +79,24 @@ describe('Image', function () { expect(rect.height).toBe(200); }); + it('Should trigger `onload` event even if hit cache', function (done) { + const imgSource = new HTMLImageElement(); + imgSource.width = 100; + imgSource.height = 50; + imgSource.src = '#'; + const mockOnload = jest.fn(); + const fakeHostEl = { + dirty: () => {} + }; + + // 模拟测试Image加载 + (global as any).Image = Image; + createOrUpdateImage(imgSource.src, imgSource as any, fakeHostEl, mockOnload); + createOrUpdateImage(imgSource.src, imgSource as any, fakeHostEl, mockOnload); + + setTimeout(() => { + expect(mockOnload).toHaveBeenCalledTimes(2); + done(); + }, 200); + }); }); \ No newline at end of file