用鼠标旋转固定大小的线条
Rotate line with fixed size by mouse
我正试图在台球游戏中创建类似球杆的东西,需要用鼠标旋转固定大小的线。
我希望鼠标位置后面的那条线是固定的,例如100个像素。
演示:http://jsfiddle.net/DAEpy/1/
我尝试使用rotate()
函数来执行此操作,但它会旋转所有画布。
所以,我的线有一个固定的末端和固定的大小(可能是100像素),它将跟随鼠标。
谢谢。
只需确定直线起点和鼠标位置之间的角度:
var dx = mouse.x - line.x1,
dy = mouse.y - line.y1,
angle = Math.atan2(dy, dx);
然后使用100像素半径渲染线条:
line.x2 = line.x1 + 100 * Math.cos(angle);
line.y2 = line.y1 + 100 * Math.sin(angle);
Demo
var ctx = document.querySelector("canvas").getContext("2d"),
line = {
x1: 150, y1: 70,
x2: 0, y2: 0
},
length = 100;
window.onmousemove = function(e) {
//get correct mouse pos
var rect = ctx.canvas.getBoundingClientRect(),
x = e.clientX - rect.left,
y = e.clientY - rect.top;
// calc line angle
var dx = x - line.x1,
dy = y - line.y1,
angle = Math.atan2(dy, dx);
//Then render the line using 100 pixel radius:
line.x2 = line.x1 + length * Math.cos(angle);
line.y2 = line.y1 + length * Math.sin(angle);
// render
ctx.clearRect(0, 0, 300, 150);
ctx.beginPath();
ctx.moveTo(line.x1, line.y1);
ctx.lineTo(line.x2, line.y2);
ctx.stroke()
}
<canvas></canvas>
相关文章:
- 将鼠标旋转限制为特定的度数
- CSS 图标旋转 鼠标关闭时的第二个动画
- 旋转实体以查看鼠标(Craftyjs)
- 如何检查鼠标点击是否位于JavaScript中HTML5画布上的旋转文本内
- 用鼠标旋转固定大小的线条
- 在 html5 画布中用鼠标旋转图像
- 三.js将盒子旋转到鼠标位置不起作用
- HTML5 画布 - 使用鼠标按锚点旋转
- 使用鼠标滚动 kineticjs 旋转矩形
- 如何使用 Raphael.js 在每次单击鼠标时触发旋转动画
- 纸张.js围绕枢轴旋转组鼠标拖动
- 使用 JavaScript 将鼠标悬停在 JavaScript 上时停止一组旋转的对象
- 如何停止旋转鼠标上的轮子和警报值
- 左右滚轮旋转的水平鼠标滚轮事件
- Three.js-鼠标移动时沿(0,0,0)旋转对象
- 如何在同一时间和同一鼠标事件上旋转两个不同的X3D场景
- Netflix风格的图像连续旋转木马,鼠标悬停,支持Bootstrap
- CSS3变换使用鼠标位置旋转
- 用鼠标旋转物体?(无mouseDown)
- JavaScript和HTML5 -向鼠标旋转字符