javascript - 如何防止画布绘图在下一次鼠标按下时被擦除?
问题描述
我在 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;
}
当我完成一条线时,我松开按钮,再次绘制将擦除之前的绘制
解决方案
重置 2D 上下文状态
当您设置画布大小时,2D 状态将重置为默认值。这包括所有设置为默认值的像素transparent
(或者black
如果您{alpha: false}
在获取上下文时使用)。
此外,所有 2D 设置(如fillStyle
、font
、transform
等)都重置为默认值。
任何通过保存的状态ctx.save
也会被删除。
width
对画布或height
属性的任何写入都会发生这种情况。
例如,以下将重置画布状态。
canvas.width = canvas.width;
在您的通话startDrawing
中,您设置了画布width
,height
这就是您的画布在每次鼠标按下事件时都被清除的原因。
推荐阅读
- php - 基于键将数组项合并为一个具有三层的数组
- python - Django annotate 无法计算 Sum - 是一个聚合
- python - 递增顺序 Python
- laravel - 如何使用php从laravel中的json数据中分解以下值
- pyspark - DStream 确实使用 Pyspark 在 Spark Streaming 中保存空文件
- c# - 可以删除禁用字段集中的 IE 11.1324 文本。ASP.NET
- xml - 如何在odoo中编辑银行账户类型
- excel - 使用 vba 在更改数据透视字段名称时对更新数据透视进行排序
- c# - C#/.Net 代码以屏幕捕获具有缩放的多个监视器
- d3.js - 使用折线图定义函数的 D3.js 问题