<canvas id="canvas1" width=300 height=300></canvas>
<script type="text/javascript">
var canvas1 = document.getElementById("canvas1");
var context1 = canvas1.getContext("2d");
var mouseX;
var mouseY;
var cx = 150; // 回転中心X座標
var cy = 150; // 回転中心Y座標
var rw = 150; // 四角形横幅
var rh = 50; // 四角形縦幅
var rot = 0.0;
// (0, 0)が中心の横幅w, 縦幅hの四角形がrラジアン回転している場合に、
// (x, y)の点が四角形に衝突しているかどうか
function hitPoint(x, y, w, h, r) {
var s = Math.sin(-r);
var c = Math.cos(-r);
var xx = Math.abs(x*c - y*s);
var yy = Math.abs(x*s + y*c);
if(xx < w/2.0 && yy < h/2.0) {
return true;
}
return false;
}
function getMouseXY(e) {
var r = e.target.getBoundingClientRect();
mouseX = e.clientX - r.left;
mouseY = e.clientY - r.top;
}
function rotateRect() {
context1.clearRect(0, 0, canvas1.width, canvas1.height);
context1.save();
context1.translate(cx, cy);
var rval = Math.PI*rot;
context1.rotate(rval);
context1.translate(-rw/2.0, -rh/2.0);
if(hitPoint(mouseX-cx, mouseY-cy, rw, rh, rval)) {
context1.fillStyle = "rgb(0, 0, 255)";
}
else {
context1.fillStyle = "rgb(255, 0, 0)";
}
context1.fillRect(0, 0, 150, 50);
context1.restore();
rot += 0.02;
}
canvas1.onmousemove = getMouseXY;
setInterval(rotateRect, 10);
</script>