我的问题是红线的初始化旋转了一个等于黄线的角度... 我想让这个角度仅在开始时等于零(红线角度)。 **然后在鼠标移动时旋转。 。
这里我是如何画线的
var x = W / 2;
var y = H / 2;
var lineLength = 900;
ctx.save();
ctx.translate(x, y);
ctx.rotate(((0.003 * (mouse.x - p.w))/2)) ; // how to increment the angle ??
ctx.moveTo(-lineLength / 2,0, 0);
ctx.lineTo(lineLength / 2.0, 0);
ctx.stroke();
ctx.restore();
答案 0 :(得分:0)
代码中的小故障:确保使用context.beginPath();
开始每个路径绘制操作以下是围绕其中点旋转线条的方法:
function draw(angle){
ctx.clearRect(0,0,cw,ch);
ctx.save();
// draw rotated line
ctx.translate(cx,cy);
ctx.rotate(angle) ;
ctx.beginPath();
ctx.moveTo(-lineLength/2,0)
ctx.lineTo(lineLength/2,0);
ctx.strokeStyle='orange';
ctx.stroke();
ctx.restore();
}
示例代码和演示:http://jsfiddle.net/m1erickson/3g0yvLov/
<!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 cw=canvas.width;
var ch=canvas.height;
var $canvas=$("#canvas");
var canvasOffset=$canvas.offset();
var offsetX=canvasOffset.left;
var offsetY=canvasOffset.top;
ctx.lineWidth=10;
var cx=canvas.width/2;
var cy=canvas.height/2;
var lineLength = 90;
$("#canvas").mousemove(function(e){handleMouseMove(e);});
function draw(angle){
ctx.clearRect(0,0,cw,ch);
ctx.save();
// draw unrotated line
ctx.beginPath();
ctx.moveTo(cx-lineLength/2,cy)
ctx.lineTo(cx+lineLength/2,cy);
ctx.strokeStyle='red';
ctx.stroke();
// draw rotated line
ctx.translate(cx,cy);
ctx.rotate(angle) ;
ctx.beginPath();
ctx.moveTo(-lineLength/2,0)
ctx.lineTo(lineLength/2,0);
ctx.strokeStyle='orange';
ctx.stroke();
ctx.restore();
}
function handleMouseMove(e){
e.preventDefault();
e.stopPropagation();
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
// Put your mousemove stuff here
var dx=mouseX-cx;
var dy=mouseY-cy;
var radianAngle=Math.atan2(dy,dx);
draw(radianAngle);
}
}); // end $(function(){});
</script>
</head>
<body>
<canvas id="canvas" width=300 height=300></canvas>
</body>
</html>