My problem is that the inintialization of the red line is rotated by an angle equal to the yellow line ... I want to make this angle equal zero (red line angle ) in the begining only. ** then rotate as the mouse move. .
here how I draw the line
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();
A glitch in your code: Be sure you start each path drawing operation with context.beginPath();
Here's how to rotate a line around its midpoint:
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();
}
Example code and a Demo: 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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.