当我为角度输入新值时,线条会快速重新绘制,但随后会消失。我认为可能是输入值被刷新并再次设置为undefined但我不确定。如何使线条保持正确的角度。
<script language="javascript" type="text/javascript">
//Global Variables
rad2deg = 180/(Math.PI);
var mouse = {
x: -1,
y: -1
};
function findAngle(e){
var ang = (Math.atan((720-mouse.y)/(e.pageX-mouse.x)))*rad2deg;
$("#angle").val(ang+"°");
}
function Draw(firstX, firstY, lastX){
cvs = $("canvas")[0].getContext("2d");
cvs.clearRect(0,0,1080,720);
cvs.beginPath();
cvs.moveTo(firstX, firstY);
cvs.lineTo(lastX, 720);
cvs.closePath();
cvs.lineWidth=5;
cvs.stroke();
};
function drawUserAngle(){
enter = 0;
mod = enter % 2;
alert($("#angle").val());
var angle = $("#angle").val()/rad2deg;
if($("#angle").val() !== 'undefined'){
var x = 540 - (180/(Math.tan(angle)));
Draw(x,540,540);
}
}
$(document).ready(function(){
$("canvas").click(function(e){
if(mouse.x != -1 && mouse.y != -1){
Draw(mouse.x, mouse.y, e.pageX);
findAngle(e);
mouse.x = -1;
mouse.y = -1;
}else{
mouse.x = e.pageX;
mouse.y = e.pageY;
}
});
});
</script>
<form>
Angle: <input type="text" id="angle">
<button onclick="drawUserAngle()">Enter</button>
答案 0 :(得分:0)
单击按钮时的标准操作是执行提交。您可以通过更改
来禁用此功能<button onclick="drawUserAngle()">Enter</button>
到
<button onclick="drawUserAngle(); return false">Enter</button>
简要描绘该行的原因是页面在提交时刷新。