![](/img/trans.png)
[英]How to make find the angle one object must rotate at to face another, JS HTML5 CANVAS
[英]How can I increment the rotation angle for a JS object in HTML5 canvas?
我的问题是,将红线的初始化旋转等于黄线的角度... 我想仅在开始时使该角度等于零(红线角度)。 **,然后随着鼠标移动旋转。 。
在这里我如何画线
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();
代码中的故障:确保使用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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.