javascript - 清除没有画布的 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>"
}
解决方案
而不是追加一个新的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>"
}
推荐阅读
- mysql - 有两个表Mysql的条件查询
- jquery - 不允许用户取消选择 WooCommerce 中的变体
- c# - ASP.NET Core 2 Windows 身份验证/AD 获取组成员
- python - 输出中的进度条取决于 Python 中的计算进度
- java - 我可以在 java 中使用注释来执行一些操作,例如来自表单的值的大写。
- jquery - Jquery - 这个id作为变量
- android - 在 AsyncTask 中使用 Glide v4 为 RecyclerView 预加载图像
- ibeacon - 使用 AltBeacon 库从 Android 上的 iBeacon 读取传感器值
- kotlin - 在 Kotlin 中创建实例,如果不为空,则仅设置属性
- c - 使用 fopen 写入文件不起作用