gpt4 book ai didi

Javascript Canvas 重绘,但我看到之前绘制的矩形

转载 作者:行者123 更新时间:2023-12-03 03:36:46 24 4
gpt4 key购买 nike

我尝试在 HTML Canvas 上不断重绘矩形,就像选择特定区域一样。

当我移动鼠标指针(同时按下鼠标键)时,我调用redraw,它会清除 Canvas 并重新绘制与全局存储的坐标相对应的矩形。

由于每次鼠标事件都会清除 Canvas ,因此我预计 Canvas 中只会得到一个矩形,但我得到了太多矩形。

这是我的代码:

<canvas id="image" width="0" height="0" style="background-color: orange"></canvas>
<script>
var mousedown = false;
var x1;
var y1;
var x2;
var y2;
document.getElementById("image").onmousedown = function(e) {
mousedown = true;
x1 = e.offsetX;
y1 = e.offsetY;
console.log(e.offsetX);
console.log(e.offsetY);
var canvas = document.getElementById("image")
var context = canvas.getContext("2d");
context.clearRect(0, 0, canvas.width, canvas.height);
console.log('clean');
}
document.getElementById("image").onmouseup = function(e){
mousedown = false;
}
document.getElementById("image").onmousemove = function(e) {
if (mousedown) {
x2 = e.offsetX;
y2 = e.offsetY;
redraw()
}
}

function redraw() {
var canvas = document.getElementById("image")
var context = canvas.getContext("2d");
context.clearRect(0, 0, canvas.width, canvas.height);
context.rect(x1, y1, (x2 - x1), (y2 - y1));
context.stroke();
}
</script>

结果是:

enter image description here

为什么我会得到这么多矩形,如何才能得到最后一个?(或者如何在没有任何库的情况下更有效地完成它?)

最佳答案

您的问题不在于clearRect方法,问题在于当您希望在 Canvas 上绘图时需要开始一个路径。

在 context.rect(); 上方添加 context.beginPath();

jsFiddle

一些重要问题已经在这里得到解答:
clearRect not working

这些文章也非常适合 Canvas 操作: http://cheatsheetworld.com/programming/html5-canvas-cheat-sheet/ https://www.w3schools.com/tags/ref_canvas.asp

关于Javascript Canvas 重绘,但我看到之前绘制的矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45821541/

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