Closed. This question is off-topic。它当前不接受答案。
                            
                        
                    
                
                            
                                
                
                        
                            
                        
                    
                        
                            想改善这个问题吗? Update the question,所以它是on-topic,用于堆栈溢出。
                        
                        2年前关闭。
                                                                                            
                
        
我正在尝试创建一个实时渲染框,可以在其中单击并拖动以进行缩放。我找到了这个例子

http://jsfiddle.net/d9BPz/546/

但是当我在本地运行时,什么也没出现。我认为这与CSS样式有关。我以为您不允许给JS变量CSS样式。

.rectangle {
border: 1px solid #FF0000;
position: absolute;
}


我确保在索引文件中正确添加了javascript和css文件。

最佳答案

在本地计算机中,在<div id="canvas"></div>之后在主体中编写脚本

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


您正在获取异常,因为它试图在加载画布对象之前设置onmouseover事件。

09-25 18:04