【问题标题】:Javascript Canvas Redrawing But I See Previously Drawn RectanglesJavascript 画布重绘但我看到以前绘制的矩形
【发布时间】:2017-08-22 15:20:18
【问题描述】:

我正在尝试在 HTML 画布上重新绘制矩形,就好像我在选择特定区域一样。

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

由于每次鼠标事件都会清除画布,我希望画布中只有一个矩形,但我得到的矩形太多了。

这是我的代码:

<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>

结果是:

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

【问题讨论】:

  • 能否更新canvas.width和canvas.height的console.log值问题?
  • 为什么要把cavas设置成这样width="0" height="0"?
  • @artgb 我登录并检查过,但我认为它们没有改变......
  • @artgb 啊,要根据图片大小改一下。

标签: javascript html


【解决方案1】:

你的问题不在于 clearRect 方法,问题是你需要在画布上绘制时开始一个 Path。

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

jsFiddle

这里已经回答了一些很好的问题:
clearRect not working

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

【讨论】:

  • 天才!非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-01
相关资源
最近更新 更多