gpt4 book ai didi

javascript - 如何在 Canvas 上绘制多个半透明矩形?

转载 作者:搜寻专家 更新时间:2023-10-31 23:26:37 29 4
gpt4 key购买 nike

我在 Canvas 上有一张图片,我想在上面绘制半透明的矩形。我通过用一根手指拖放来逐步绘制它们。

现在我的代码是这样的:

...

function handleTouch(event) {
if (event.targetTouches.length === 1) {
touch = event.targetTouches[0];

if (event.type == 'touchmove') {
if (drag) {
rect.w = touch.pageX - rect.startX;
rect.h = touch.pageY - rect.startY ;
draw();
}
} else {
rect.startX = touch.pageX;
rect.startY = touch.pageY;
drag = true;
}
}
}

function handleEnd(event) {
drag = false;
}

function draw() {
drawImageOnCanvas();
ctx.strokeStyle = "green";
ctx.strokeRect(rect.startX, rect.startY, rect.w, rect.h);
ctx.fillStyle = 'rgba(0, 100, 255, 0.1)';
ctx.fillRect(rect.startX, rect.startY, rect.w, rect.h);
}

function drawImageOnCanvas() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(imgObj, 0, 0);
}

现在它一次只对一个矩形有效,它看起来像我想要的,但我想要更多。我该怎么办?

最佳答案

难道只保留一个矩形数组然后遍历它们是不可能的,因为您每次都需要重绘它吗?

...
var rects = [];

function handleTouch(event) {
if (event.targetTouches.length === 1) {
touch = event.targetTouches[0];

if (event.type == 'touchmove') {
if (drag) {
rects[rects.length-1].w = touch.pageX - rect.startX;
rects[rects.length-1].h = touch.pageY - rect.startY ;
draw();
}
} else {
rects.push({
startX: 0,
startY: 0,
w: 0,
h: 0
});
rects[rects.length-1].startX = touch.pageX;
rects[rects.length-1].startY = touch.pageY;
drag = true;
}
}
}

function handleEnd(event) {
drag = false;
}

function draw() {
drawImageOnCanvas();
for (var i in rects) {
var rect = rects[i];
ctx.strokeStyle = "green";
ctx.strokeRect(rect.startX, rect.startY, rect.w, rect.h);
ctx.fillStyle = 'rgba(0, 100, 255, 0.1)';
ctx.fillRect(rect.startX, rect.startY, rect.w, rect.h);
}
}

function drawImageOnCanvas() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(imgObj, 0, 0);
}

关于javascript - 如何在 Canvas 上绘制多个半透明矩形?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30010479/

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