0

我需要使用画布的全部空间来绘制。但是这里无法使用画布的顶部和左侧进行绘制。我尝试对css进行一些更改,但仍然没有运气。请帮忙。ps 通过单击按钮,画布将弹出。

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

1 回答 1

0

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

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

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

该变量e引用 mouseEvent 对象。e.pageX 表示鼠标与页面左侧之间的距离,而不是您的画布。所以你应该减去画布的左偏移,mx然后对 做同样的事情my,这样绘图点就在你想要的地方。

一种简单的解决方案:将画布的margin,border和设置padding为 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!
}
于 2013-06-18T07:03:28.950 回答