画布 - 旋转路径

时间:2014-10-08 22:48:57

标签: javascript canvas rotation line

我想知道如何在画布中旋转一条线。 说我有画布设置。

ctx.beginPath();
ctx.strokeStyle = "#000000";
ctx.moveTo(p1.x, p1.y);
ctx.lineTo(p2.x, p2.y);
ctx.stroke();
ctx.closePath();

如何旋转此线?

谢谢,

亚历

2 个答案:

答案 0 :(得分:0)

以下是如何在p1和&之间旋转线段p2围绕该段的中点:

这个想法是:

  • 使用context.save

  • 保存上下文的未旋转状态
  • 使用context.translate

  • 在线条的中点设置旋转点
  • 使用context.rotate

  • 旋转到指定的弧度角
  • 画线。这是棘手的部分......由于画布已经旋转,并且由于画布原点现在是线的中点,因此必须moveTo减去线的长度/ 2并且lineTo线长度/ 2: context.moveTo(-length/2,0);context.lineTo(length/2,0);

  • 使用context.restore

  • 将上下文恢复为未启动状态

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;

var p1={x:75,y:75};
var p2={x:150,y:150};
var dx=p2.x-p1.x;
var dy=p2.y-p1.y;
var length=Math.sqrt(dx*dx+dy*dy);
var angle=Math.atan2(dy,dx);
var midX=(p2.x+p1.x)/2;
var midY=(p2.y+p1.y)/2;

console.log(midX,midY);

draw(angle);

requestAnimationFrame(animate);

function animate(time){
  requestAnimationFrame(animate);
  draw(angle);
  angle+=Math.PI/30;
}


function draw(radianAngle){
  ctx.clearRect(0,0,canvas.width,canvas.height);
  ctx.save();
  ctx.translate(midX,midY);
  ctx.rotate(radianAngle);
  ctx.beginPath();
  ctx.strokeStyle='red';
  ctx.moveTo(-length/2,0);
  ctx.lineTo(length/2,0);
  ctx.stroke();
  ctx.restore();
}
body{ background-color: ivory; }
canvas{border:1px solid red;}
<canvas id="canvas" width=300 height=300></canvas>

注意:此代码显示围绕线条中点的旋转,但您可以使用context.translate(anyRotationPointX,anyRotationPointY);

围绕任意点旋转

答案 1 :(得分:0)

要旋转任何内容,您可以使用上下文方法 - rotate()。 我们不能像对象一样旋转线(如在SVG中),但我们可以 - 用新的旋转线重绘画布。

var canvas = document.getElementById("example"), 
    ctx = example.getContext('2d'),
    canvasWidth = canvas.width,
    canvasHeight = canvas.height,
    p1 = {x:canvasWidth/2+50,y:canvasHeight/2},
    p2 = {x:p1.x,y:p1.y+100},
    middlePoint = {x:(p1.x+p2.x)/2,y:(p1.y+p2.y)/2};

function rotate(degree,rotatePoint,drFunc) {
    rotatePoint = rotatePoint || {x:canvasWidth/2,y:canvasHeight/2};
    // Clear the canvas
    ctx.clearRect(0, 0, canvasWidth, canvasHeight);

    // Move registration point to the center of the canvas
    ctx.translate(rotatePoint.x, rotatePoint.y);

    // Rotate 1 degree
    ctx.rotate((Math.PI / 180)*degree);

    // Move registration point back to the top left corner of canvas
    ctx.translate(-rotatePoint.x, -rotatePoint.y);

    drFunc();
}

function drFunc(){
    ctx.beginPath();
    ctx.strokeStyle = "black";
    ctx.moveTo(p1.x, p1.y);
    ctx.lineTo(p2.x, p2.y);
    ctx.stroke();
    ctx.closePath();
}

rotate(1,middlePoint,drFunc);

Fiddle

相关问题