首页 > 解决方案 > 清除没有画布的 HTML 页面

问题描述

我想知道是否有任何方法可以在不使用画布的情况下清除 HTML 页面。

我正在尝试使用没有画布的 JavaScript 制作一个简单的程序,它从窗口中心画一条线到鼠标指向的任何地方。无论何时何地鼠标移动,我都可以成功绘制一条新线,但不知道如何在不制作画布和使用clearRect().

有没有办法在没有画布的情况下清除页面?

以防万一有人觉得它有帮助,这是我的代码:

      window.addEventListener('mousemove', function (e){
      linedraw(window.innerWidth/2, window.innerHeight/2, e.x, e.y)
      });

      function linedraw(x1, y1, x2, y2) {
    if (x2 < x1) {
        tmp = x2 ; x2 = x1 ; x1 = tmp
        tmp = y2 ; y2 = y1 ; y1 = tmp
    }

    lineLength = Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
    m = (y2 - y1) / (x2 - x1)

    degree = Math.atan(m) * 180 / Math.PI

    document.body.innerHTML += "<div class='line' style='transform-origin: top left; transform: rotate(" + degree + "deg); width: " + lineLength + "px; height: 1px; background: black; position: absolute; top: " + y1 + "px; left: " + x1 + "px;'></div>"
}

标签: javascriptcanvasrefresh

解决方案


而不是追加一个新的div,只需在每次鼠标移动时替换 html。

window.addEventListener('mousemove', function (e){
    linedraw(window.innerWidth/2, window.innerHeight/2, e.x, e.y)
});

function linedraw(x1, y1, x2, y2) {
    if (x2 < x1) {
        tmp = x2 ; x2 = x1 ; x1 = tmp
        tmp = y2 ; y2 = y1 ; y1 = tmp
    }

    lineLength = Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
    m = (y2 - y1) / (x2 - x1)

    degree = Math.atan(m) * 180 / Math.PI

    // `document.body.innerHTML = ` instead of `document.body.innerHTML += `
    document.body.innerHTML = "<div class='line' style='transform-origin: top left; transform: rotate(" + degree + "deg); width: " + lineLength + "px; height: 1px; background: black; position: absolute; top: " + y1 + "px; left: " + x1 + "px;'></div>"
}


推荐阅读