代碼中的故障:要確保你開始每個路徑繪製操作與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>
請描述你更好想要達到的目標。 – markE 2014-10-05 21:08:09
我現在編輯帖子。 – john 2014-10-05 21:08:31
感謝您的澄清:-)我發佈了一個符合您需求的答案。此外,請確保使用context.beginPath開始所有路徑操作 - 否則,您的所有前面的行將使用每個context.stroke命令重新繪製。 – markE 2014-10-05 21:36:24