You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular画布调整尺寸后无法重绘图形问题求助

解决方案

问题根源

调整画布尺寸时,Canvas元素的width/height属性发生变更,浏览器会自动重置该Canvas的绘图上下文(CanvasRenderingContext2D),你之前在ngOnInit中缓存的this.context会变为无效对象,此时用它执行绘制操作不会在画布上产生任何效果。而修改元素坐标时,画布尺寸未变,上下文保持有效,因此重绘能正常生效。

修复代码

修改redrawLabel方法,每次更新画布尺寸后重新获取有效上下文:

redrawLabel(result: ISerialLabelDesign) {
    console.log('inside redrawLabel');    
    const canvas: HTMLCanvasElement = this.myCanvas.nativeElement;
    // 计算像素尺寸并同步到Canvas元素
    this.defaultLabelWidth = result.labelWidth * 3.7795;
    this.defaultLabelHeight = result.labelHeight * 3.7795;
    canvas.width = this.defaultLabelWidth;
    canvas.height = this.defaultLabelHeight;
    // 重新获取有效绘图上下文
    this.context = canvas.getContext('2d');
    
    this.clearDrawing();
    this.shapesToDrawArray.length = 0;
    this.storeDrawing(result);          
    this.startDrawing(this.shapesToDrawArray);
}

额外提示

  • 若你通过Angular属性绑定(如<canvas #myCanvas [width]="defaultLabelWidth" [height]="defaultLabelHeight"></canvas>)同步画布尺寸,需确保在尺寸更新后重新获取上下文,因为属性绑定触发的尺寸变更同样会重置上下文。
  • 检查clearDrawing方法,确保它使用的是最新的this.context,避免用失效上下文执行清空操作。

内容的提问来源于stack exchange,提问作者ZAJ

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 04:39:54