2014-10-05 58 views
0

我的問題是,紅線的初始化是旋轉了一個角度等於黃線... 我想在這個角度等於零(紅線角度)只在開始。 **然後隨着鼠標移動而旋轉。 enter image description here如何在HTML5畫布中增加JS對象的旋轉角度?

這裏我如何拿捏

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

請描述你更好想要達到的目標。 – markE 2014-10-05 21:08:09

+0

我現在編輯帖子。 – john 2014-10-05 21:08:31

+1

感謝您的澄清:-)我發佈了一個符合您需求的答案。此外,請確保使用context.beginPath開始所有路徑操作 - 否則,您的所有前面的行將使用每個context.stroke命令重新繪製。 – markE 2014-10-05 21:36:24

回答

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> 
+0

它運作良好..謝謝 – john 2014-10-06 02:37:41