首页 > 解决方案 > 如何防止画布绘图在下一次鼠标按下时被擦除?

问题描述

我在 Ionic 3 angular V5 上,我无法使用返回未定义的 Viewchild,所以我使用 ViewChildren 获取数组的第一项(我知道很脏)

@ViewChildren('imageCanvas') canvas: any;
public canvasElement: any;
saveX: number;
saveY: number;
public drawing = false;
selectedColor: '#9e2956';
lineWidth: 5;

startDrawing(ev) {
    if (this.canvasElement === undefined) {
        this.canvasElement = this.canvas._results[0].nativeElement;
        console.log('always there')
    }
    this.canvasElement.width = this.plt.width() + '';
    this.canvasElement.height = 200;

    const canvasPosition = this.canvasElement.getBoundingClientRect();
    let currentX = ev.pageX - canvasPosition.x;
    let currentY = ev.pageY - canvasPosition.y;
    this.saveX = currentX;
    this.saveY = currentY;

    this.drawing = true
}

moved(ev) {
    if (!this.drawing) return


    const canvasPosition = this.canvasElement.getBoundingClientRect();

    //console.log('canvasPosition ', canvasPosition)

    let ctx = this.canvasElement.getContext('2d');

    let currentX = ev.pageX - canvasPosition.x;
    let currentY = ev.pageY - canvasPosition.y;

    ctx.lineJoin = 'round';
    ctx.strokeStyle = this.selectedColor;
    ctx.lineWidth = this.lineWidth;

    ctx.beginPath();
    ctx.moveTo(this.saveX, this.saveY);
    ctx.lineTo(currentX, currentY);
    ctx.closePath();

    ctx.stroke();

    this.saveX = currentX;
    this.saveY = currentY;


}

当我完成一条线时,我松开按钮,再次绘制将擦除之前的绘制

标签: javascriptangularcanvasionic3

解决方案


重置 2D 上下文状态

当您设置画布大小时,2D 状态将重置为默认值。这包括所有设置为默认值的像素transparent(或者black如果您{alpha: false}在获取上下文时使用)。

此外,所有 2D 设置(如fillStylefonttransform等)都重置为默认值。

任何通过保存的状态ctx.save也会被删除。

width对画布或height属性的任何写入都会发生这种情况。

例如,以下将重置画布状态。

 canvas.width = canvas.width;

在您的通话startDrawing中,您设置了画布widthheight这就是您的画布在每次鼠标按下事件时都被清除的原因。


推荐阅读