<分区>
编辑问题以包含 desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem .这将有助于其他人回答问题。
关闭 6 年前。
<分区>
编辑问题以包含 desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem .这将有助于其他人回答问题。
关闭 6 年前。
我正在尝试创建一个实时渲染框,我可以在其中单击并拖动以进行缩放。我找到了这个例子,
http://jsfiddle.net/d9BPz/546/
但是当我在本地运行它时,什么也没有出现。我认为这与 CSS 样式有关。我以为你不允许给 JS 变量 CSS 样式。
.rectangle {
border: 1px solid #FF0000;
position: absolute;
}
我确保在索引文件中正确添加了 javascript 和 css 文件。
最佳答案
在您的本地机器上,在<div id="canvas"></div>
之后的body 中编写脚本
<html>
<head>
<style>
#canvas {
width:2000px;
height:2000px;
border: 10px solid transparent;
}
.rectangle {
border: 1px solid #FF0000;
position: absolute;
}
</style>
</head>
<body>
<div id="canvas"></div>
<script>
initDraw(document.getElementById('canvas'));
function initDraw(canvas) {
function setMousePosition(e) {
var ev = e || window.event; //Moz || IE
if (ev.pageX) { //Moz
mouse.x = ev.pageX + window.pageXOffset;
mouse.y = ev.pageY + window.pageYOffset;
} else if (ev.clientX) { //IE
mouse.x = ev.clientX + document.body.scrollLeft;
mouse.y = ev.clientY + document.body.scrollTop;
}
};
var mouse = {
x: 0,
y: 0,
startX: 0,
startY: 0
};
var element = null;
canvas.onmousemove = function (e) {
setMousePosition(e);
if (element !== null) {
element.style.width = Math.abs(mouse.x - mouse.startX) + 'px';
element.style.height = Math.abs(mouse.y - mouse.startY) + 'px';
element.style.left = (mouse.x - mouse.startX < 0) ? mouse.x + 'px' : mouse.startX + 'px';
element.style.top = (mouse.y - mouse.startY < 0) ? mouse.y + 'px' : mouse.startY + 'px';
}
}
canvas.onclick = function (e) {
if (element !== null) {
element = null;
canvas.style.cursor = "default";
console.log("finsihed.");
} else {
console.log("begun.");
mouse.startX = mouse.x;
mouse.startY = mouse.y;
element = document.createElement('div');
element.className = 'rectangle'
element.style.left = mouse.x + 'px';
element.style.top = mouse.y + 'px';
canvas.appendChild(element)
canvas.style.cursor = "crosshair";
}
}
}
</script>
</body>
</html>
您遇到异常是因为它试图在加载 Canvas 对象之前设置 onmouseover 事件。
关于javascript - 代码在 JSfiddle 中有效,但在本地主机上无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42012950/