gpt4 book ai didi

javascript - 创建 Circles(div) 并将其附加到 div#canvas

转载 作者:行者123 更新时间:2023-12-03 08:28:21 26 4
gpt4 key购买 nike

当我的笔悬停在窗口上时,我正在尝试创建新的圆圈。我遇到无法向页面添加圈子的问题。它只是徘徊。我如何修改我的代码以在悬停时添加圆圈。

<!doctype html>
<html>
<head>
<title> JavaScript Environment: Project </title>
<meta charset="utf-8">
<style>
html, body {
width: 100%;
height: 100%;
margin: 0px;
padding: 0px;
}
#canvas {
background-color: yellow;
width: 100%;
height: 100%;
}
.pen {
position: absolute;
background-color: lightblue;
width: 10px;
height: 10px;
border-radius: 5px;
}
</style>
<script>
window.onload = function() {
function Circle(x, y) {
this.x = x;
this.y = y;
}
var canvas = document.getElementById("canvas");

canvas.onmousedown = function() {
mouseDown();
};
canvas.onmouseup = function() {
mouseUp()
};
canvas.onmousemove = function() {
mouseMove(event)
};
function mouseDown (){
console.log ("mouse down");
}
function mouseUp (){
console.log ("mouse up");
}
function mouseMove(e) {
var canvas = document.getElementById("canvas");
var pen = document.createElement("div");
var x = e.clientX;
var y = e.clientY;
var coor = "Coordinates: (" + x + "," + y + ")";
pen.setAttribute("class", "pen");
pen.style.left = x + "px";
pen.style.top = y + "px";
document.getElementById("canvas").innerHTML = coor;
canvas.appendChild(pen);
addCircles(x, y);

console.log("location @ " + x + " : " + y);

}
function addCircles(x, y) {
var canvas = document.getElementById("canvas");
var circle = document.createElement("div");
circle.setAttribute("class", "pen");
circle.style.left = x + "px";
circle.style.top = y + "px";
canvas.appendChild(circle);

}
canvas.addEventListener("mouseMove", mouseMove, false);
};
</script>
</head>
<body>
<div id="canvas"></div>
</body>
</html>

最佳答案

问题出在 document.getElementById("canvas").innerHTML = coor; 行中

尝试添加跨度 <span id="canvasText"></span>在你的 Canvas div 里面,然后将上面的行更改为 document.getElementById("canvasText").innerHTML = coor; .

就目前情况而言,每次鼠标移动时,您都会“重置” Canvas 的内容,因此圆圈会立即从中删除。仅重置 Canvas 内的跨度以保留圆圈。

关于javascript - 创建 Circles(div) 并将其附加到 div#canvas,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33447607/

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