/*
 * @Author: zhoux zhouxia@supervision.ltd
 * @Date: 2023-12-05 13:55:45
 * @LastEditors: zhoux zhouxia@supervision.ltd
 * @LastEditTime: 2023-12-05 15:55:58
 * @FilePath: \react-adpro-fabric\src\pages\Fabric\canvas\objects\Gif.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { fabric } from 'fabric';
// import 'gifler';

const Gif = fabric.util.createClass(fabric.Object, {
	type: 'gif',
	superType: 'image',
	gifCanvas: null,
	isStarted: false,
	initialize(options: any) {
		options = options || {};
		this.callSuper('initialize', options);
		this.gifCanvas = document.createElement('canvas');
	},
	drawFrame(ctx: CanvasRenderingContext2D, frame: any) {
		// update canvas size
		this.gifCanvas.width = frame.width;
		this.gifCanvas.height = frame.height;
		// update canvas that we are using for fabric.js
		ctx.drawImage(frame.buffer, -frame.width / 2, -frame.height / 2, frame.width, frame.height);
	},
	_render(ctx: CanvasRenderingContext2D) {
		this.callSuper('_render', ctx);
		if (!this.isStarted) {
			this.isStarted = true;
			window
				// @ts-ignore
				.gifler('./images/sample/earth.gif')
				.frames(this.gifCanvas, (_c: CanvasRenderingContext2D, frame: any) => {
					this.isStarted = true;
					this.drawFrame(ctx, frame);
				});
		}
	},
});

Gif.fromObject = (options: any, callback: (obj: any) => any) => {
	return callback(new Gif(options));
};

// @ts-ignore
window.fabric.Gif = Gif;

export default Gif;
