无法使用画布的整个空间

时间:2013-06-18 06:30:52

标签: javascript html css

我需要使用画布的完整空间来绘制。但是这里无法使用画布的顶部和左侧绘制。我尝试在CSS中做一些改动,但仍然没有运气。请帮忙。 附:通过单击按钮,将弹出画布。

<button onClick="openPopup();">click here</button>
<div id="test" class="popup">
    <div class="cancel" onclick="closePopup();"></div>
    <canvas id="canvas1" width="750" height="720" style="border: 1px solid black"></canvas>
</div>

<style>
.popup{
    position:absolute;
    top:0px;
    left:0px;
    margin:0px;
    width: 900px;
    height: 750px;
    font-family:verdana;
    font-size:13px;
    padding:2px;
    background-color:white;
    border:2px solid grey;
    z-index:100000000000000000;
    display:none;
    opacity:0.6;
    filter:alpha(opacity=60);
    margin-left: 300px;
    margin-top: 90px; 
    overflow: auto; 
    }

.cancel{
    display:relative;
    cursor:pointer;
    margin:0;
    float:right;
    height:10px;
    width:14px;
    padding:0 0 5px 0;
    background-color:red;
    text-align:center;
    font-weight:bold;
    font-size:11px;
    color:white;
    border-radius:3px;
    z-index:100000000000000000;
    }

.cancel:hover{
    background:rgb(255,50,50);
    }
</style>
<script>
function openPopup() {
    document.getElementById('test').style.display = 'block';
}
function closePopup() {
    document.getElementById('test').style.display = 'none';
}

var can = document.getElementById('canvas1');
var ctx = can.getContext('2d');
var isPressed = false;
var mx = 4, my = 4;

function move(e) {
  getMouse(e);
  if (isPressed) {
    ctx.lineTo(mx, my);
    ctx.stroke()
  }
}

function up(e) {
  getMouse(e);
  isPressed = false;
}

function down(e) {
  getMouse(e);
  ctx.beginPath();
  ctx.moveTo(mx, my);
  isPressed = true;
}

can.onmousemove = move;
can.onmousedown = down;
can.onmouseup = up;

// waaaay oversimplified:
function getMouse(e) {
    var element = can, offsetX = 0, offsetY = 0;
    mx = e.pageX;
    my = e.pageY;

}

</script>

1 个答案:

答案 0 :(得分:0)

绘图点未与鼠标指针同步。 这就是为什么你不能在画布的左侧部分和顶部绘制的原因,因为如果你试图在左边缘附近画一些东西,鼠标已经不在画布中了。

请注意您如何获得绘图点的当前位置:

function getMouse(e) {
    var element = can, offsetX = 0, offsetY = 0;
    mx = e.pageX;
    my = e.pageY;
}

变量e指的是mouseEvent对象。和e.pageX表示鼠标与页面左侧之间的距离,而不是您的CANVAS。因此,您应该从mx减去画布的左侧偏移并对my执行相同的操作,以便绘图点位于您想要的位置。

一个简单的解决方案: 将画布的marginborderpadding设置为0;

.popup{
    //everything else..
    boder: 0;
    margin-left: 0px;
    margin-top: 0px;
    }

更好的解决方案: 减去左侧偏移到mxmy

function getMouse(e) {
    var element = can, offsetX = 0, offsetY = 0;
    mx = e.pageX - 305;
    my = e.pageY - 95;

    //Dynamically getting those padding and margin and border would be better!
}