我正在使用Angular 6
和fabricjs
渲染画布。
我有一个 CanvasService ,可以像这样处理传递的画布
export class CanvasService {
constructor() { }
renderCanvas(canvas, fbTemplate: FbAdTemplateData, pImage: string, textContent: string) {
const cvBgImage = new fabric.Image.fromURL(fbTemplate.background_image_url, imgInstance => {
imgInstance.lockMovementX = true;
imgInstance.lockMovementY = true;
imgInstance.lockScalingX = true;
imgInstance.lockScalingY = true;
imgInstance.lockRotation = true;
imgInstance.set({
width: canvas.width,
height: canvas.height,
originX: 'left',
originY: 'top'
});
canvas.setBackgroundImage(imgInstance, canvas.renderAll.bind(canvas));
});
canvas.on('mouse:down', options => {
canvas.setActiveObject(cvTextString);
cvTextString.bringToFront();
});
const cvTextString = new fabric.IText(textContent), JSON.parse(fbTemplate.text_config);
canvas.add(cvTextString);
canvas.setActiveObject(cvTextString);
const cvProductImage = new fabric.Image.fromURL(pImage, imgInstance => {
imgInstance.set({
left: fbTemplate.product_image_position_left,
top: fbTemplate.product_image_position_top
});
imgInstance.scaleToHeight = fbTemplate.product_image_scale_height;
imgInstance.scaleToWidth = fbTemplate.product_image_scale_width;
canvas.add(imgInstance);
});
}
}
在组件中,该函数的调用方式类似于
private _initializeCanvasTemplate(fbAdTemplate) {
this.canvas = new fabric.Canvas('canvas');
this.canvas.clear();
this.canvasService.renderCanvas(this.canvas, fbAdTemplate, this.productImagePathAbsolute, this.textString);
}
fbAdTemplate 包含要替换的背景图片。
它工作正常,并且画布根据 fbAdTemplate 中的数据进行渲染,但是在单击画布区域时,它将全部重置为初始模板。