我试图在鼠标移动时在画布上旋转弧,但它不起作用。
这是我的代码:
var c=document.getElementById("c");
var ctx=c.getContext('2d');
c.width=window.innerWidth;
c.height=window.innerHeight;
var width=c.width;
var height=c.height;
draw();
function draw(){
var cx=width/2;
var cy=height/2;
ctx.beginPath();
ctx.strokeStyle="#fff";
ctx.arc(cx,cy,100,0,Math.PI);
ctx.stroke();
}
document.addEventListener("mousemove",function(e){
var p1=(width/2)-e.clientX;
var p2=(height/2)-e.clientY;
var angle=Math.atan2(p2, p1);
ctx.clearRect(0,0,width,height);
ctx.beginPath();
ctx.strokeStyle="#fff";
ctx.arc(width/2,height/2,100,0,Math.PI);
// ctx.translate(width/2,height/2);
ctx.rotate(angle);
//ctx.translate(0,0);
ctx.stroke();
// ctx.restore();
},false);
它没有奏效。后来我想添加更多的对象,但是它们不应该只旋转这个半圆应该按照鼠标移动进行调整。我尝试了其他翻译的例子我已经评论过,因为它不起作用。我该如何修复我的代码呢?
答案 0 :(得分:4)
你想要一个相对于鼠标旋转的半圆吗?
这是代码和小提琴:http://jsfiddle.net/m1erickson/jJTsH/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; }
#canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var canvasOffset=$("#canvas").offset();
var offsetX=canvasOffset.left;
var offsetY=canvasOffset.top;
ctx.lineWidth=3;
ctx.strokeStyle="blue";
var cx=canvas.width/2;
var cy=canvas.height/2;
var radius=75;
function drawArc(cx,cy,mouseX,mouseY){
var dx=mouseX-cx;
var dy=mouseY-cy;
var angle=Math.atan2(dy,dx);
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.beginPath();
ctx.arc(cx,cy,radius,angle,angle+Math.PI);
ctx.stroke();
}
function handleMouseMove(e){
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
drawArc(cx,cy,mouseX,mouseY);
}
$("#canvas").mousemove(function(e){handleMouseMove(e);});
}); // end $(function(){});
</script>
</head>
<body>
<canvas id="canvas" width=300 height=300></canvas>
</body>
</html>