Angle of point on Canvas
HTML5 Canvas 상에서 클릭된 점의 각도를 출력하는 예
테스트 환경: HTML5, Eclipse, Google Chrome, Javascript
아래의 표시된 영역을 클릭하면 영역의 좌상단 모서리를 원점으로 하여 측정한 해당 지점의 각도가 표시된다.
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Event Test</title>
<style type="text/css">
#canvas1 { border:1px dotted black;}
</style>
<script type="text/javascript">
var canvas = null;
var ctx = null;
var DEG = 180/Math.PI;
var clickPt = null;
var returnedRAD = 0;
var calibratedRAD = 0;
var returnedDEG = 0;
var calibratedDEG = 0;
function Point(x, y) {
this.x = x;
this.y = y;
Point.prototype.set=function(x,y){
this.x = x;
this.y = y;
}
Point.prototype.copy=function(p){
return new Point(p.x, p.y);
}
Point.prototype.sub=function(p){
return new Point(this.x-p.x,this.y-p.y);
}
Point.prototype.length=function(){
return Math.sqrt(this.x*this.x+this.y*this.y);
}
};
window.onload = function() {
canvas = document.getElementById("canvas1");
ctx = canvas.getContext("2d");
canvas.addEventListener("mousedown",onMouseDown,true);
//canvas.addEventListener("mousemove",onMouseMove,true);
};
function onMouseDown(e){
ctx.clearRect(0,0,canvas.width, canvas.height);
var canvasX = e.pageX - this.offsetLeft;
var canvasY = e.pageY - this.offsetTop;
clickPt = new Point(canvasX, canvasY);
findHeading();
displayHeading();
}
function findHeading() {
var dot = clickPt.x*1 + clickPt.y*0;
var len = clickPt.length();
var cosVal = dot/len;
var rad = Math.acos(cosVal);
returnedRAD = rad;
var deg = rad * (180/Math.PI);
returnedDEG = deg;
if(clickPt.y<0) {//위쪽을 가리키고 있는 경우에는 각도를 보정해야 한다.
//deg = 180-deg+180;
rad = Math.PI - rad + Math.PI;
deg = rad * 180/Math.PI
}
calibratedRAD = rad;
calibratedDEG = calibratedRAD*DEG;
}
function displayHeading() {
ctx.fillStyle = "black";
ctx.font = "bold 20px sans-serif";
var deg1 = Math.round(returnedDEG);
var deg2 = Math.round(calibratedDEG);
ctx.fillText("Heading(returned):"+deg1, 100,20);
ctx.fillText("Heading(calibrated):"+deg2, 100,40);
}
</script>
</head>
<body>
<div align="center">
<canvas id="canvas1" width="400" height="300"></canvas>
</div>
</body>
</html>