gpt4 book ai didi

Angular,在鼠标事件上用 Canvas 绘制多个矩形

转载 作者:行者123 更新时间:2023-12-04 02:45:44 25 4
gpt4 key购买 nike

我正在尝试创建一个 Angular 绘图工具。我创建了一个可以在 Canvas 元素上绘制矩形的工具,该工具工作正常,但我一次只能绘制一个矩形,我只是不知道如何“清除”前一个矩形并保留在我的 Canvas 上绘制多幅图画。我无法清除很多 Canvas ,因为我要画更多的画,而不仅仅是矩形。

rectangleDrawing() {

// first coordinates when clicked
let startX = 0;
let startY = 0;

const rect = this.canvasEl.getBoundingClientRect();

fromEvent(this.canvasEl, "mousedown")
.pipe(
switchMap((e:MouseEvent) => {

startX = e.clientX - rect.left;
startY = e.clientY - rect.top;

return fromEvent(this.canvasEl, 'mousemove').pipe(

takeUntil(fromEvent(this.canvasEl, 'mouseup')),
takeUntil(fromEvent(this.canvasEl, 'mouseleave'))
)

})
).subscribe((event:MouseEvent) => {

let x = event.clientX - rect.left;
let y = event.clientY - rect.top;

let width = x - startX;
let height = y - startY;


this.setCanvasProperties(10, 'square', 'rgba(255,158,43,0.6)');

this.cx.beginPath();

// if I comment this line, the rectangles will stay, but they
// won't be clear, making multiples rectangles inside the
// main rectangle
this.cx.clearRect(0,0, this.canvasEl.width, this.canvasEl.height);

this.cx.rect(startX, startY, width, height);

this.cx.stroke();

});

}

setCanvasProperties(lineWidth, lineCap, strokeStyle) {
this.cx = this.canvasEl.getContext('2d');
this.cx.lineWidth = lineWidth;
this.cx.lineCap = lineCap;
this.cx.strokeStyle = strokeStyle;
}

这个链接就是一个很好的例子:https://jsfiddle.net/richardcwc/ukqhf54k/ ,如果你评论清晰的行,你可以看到主要问题。许多例子似乎一次只允许一个矩形。

最佳答案

鼠标松开时,您可以将绘制的矩形存储在一个数组中,然后绘制该数组和当前矩形。

首先,让我们设置数组并将宽度和高度保留为全局变量:

var width;
var height;
var drawItems = [];

然后,mouseup 函数将如下所示:

$(canvas).on('mouseup', function(e) {
mousedown = false;

drawItems.push({
x0: last_mousex,
x1: width,
y0: last_mousey,
y1: height
});
});

这是 mousemove 函数:

$(canvas).on('mousemove', function(e) {
mousex = parseInt(e.clientX-canvasx);
mousey = parseInt(e.clientY-canvasy);
if(mousedown) {
ctx.clearRect(0,0,canvas.width,canvas.height); //clear canvas

ctx.strokeStyle = 'black';
ctx.lineWidth = 10;

for(var i=0; i<drawItems.length; i++) {
ctx.beginPath();
ctx.rect(drawItems[i].x0, drawItems[i].y0, drawItems[i].x1, drawItems[i].y1);
ctx.stroke();
}

width = mousex-last_mousex;
height = mousey-last_mousey;
ctx.beginPath();
ctx.rect(last_mousex,last_mousey,width,height);
ctx.stroke();
}
//Output
$('#output').html('current: '+mousex+', '+mousey+'<br/>last: '+last_mousex+', '+last_mousey+'<br/>mousedown: '+mousedown);
});

Here是更新的 fiddle

希望对你有帮助

关于Angular,在鼠标事件上用 Canvas 绘制多个矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57341753/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com