我发现如果我没有通过window给出画布宽度和高度。内部宽度/内部高度线被绘制得远远超过实际的鼠标光标。我的意思是我不能给画布整个窗口的宽度和高度。我的意思是应该有其他div,段落等。在这里,我分别为我的画布400px和768px提供宽度和高度。它没有应有的表现。我的意思是当我尝试绘制一条线时,它显示在我的鼠标光标上方。我该如何解决?
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Game Stage</title>
<script type="text/javascript">
var i=0;
var radius=10;
var lines;
var x,y;
var now_draw=false;
var i=0;
function loadCanvas(id) {
var canvas = document.createElement('canvas');
div = document.getElementById(id);
canvas.id = "CursorLayer";
canvas.width = 400;
canvas.height = 768;
canvas.style.zIndex = 8;
canvas.style.position = "absolute";
canvas.style.border = "1px solid";
div.appendChild(canvas)
}
function nowdraw(e){
now_draw=true;
}
function drawit(e){
if(now_draw){
var ctx=document.getElementById("CursorLayer").getContext("2d");
x=e.clientX;
y=e.clientY;
if(i==0){
ctx.lineWidth=2*radius;
ctx.lineTo(x,y);
ctx.stroke();
}
if(i>0){
ctx.fillStyle="red";
ctx.beginPath();
ctx.arc(x,y,radius,0,2*Math.PI);
ctx.fill();
i=0;
}
ctx.fillStyle="red";
ctx.beginPath();
ctx.arc(x,y,radius,0,2*Math.PI);
ctx.fill();
ctx.lineWidth=2*radius;
ctx.strokeStyle="red";
ctx.beginPath();
ctx.moveTo(x,y);
}
}
function cannotdraw(){
now_draw=false;
i++;
}
window.onmousedown=nowdraw;
window.onmousemove=drawit;
window.onmouseup=cannotdraw;
</script>
</head>
<body>
<h1>draw here</h1>
<div id="divControls"></div>
<div id="divGameStage"></div>
<script type="text/javascript">
loadCanvas("divGameStage");
</script>
</body>
</html>
小提琴:jsfiddle
答案 0 :(得分:1)
使用
x = e.offsetX || e.layerX || 0;
y = e.offsetY || e.layerY || 0;
而不是
x = e.clientX;
y = e.clientY;