Javascript 画布-旋转路径

Javascript 画布-旋转路径,javascript,canvas,rotation,line,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(); 如何旋转这条线 谢谢 Alex以下是如何围绕线段的中点旋转p1和p2之间的线段: 其想法是: 使用context.Save保存上下文的未旋转状态 使用context.translate在直线的中点

我想知道如何在画布上旋转线条。 假设我有画布设置

ctx.beginPath();
ctx.strokeStyle = "#000000";
ctx.moveTo(p1.x, p1.y);
ctx.lineTo(p2.x, p2.y);
ctx.stroke();
ctx.closePath();
如何旋转这条线

谢谢


Alex

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

其想法是:

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

  • 使用
    context.translate在直线的中点设置旋转点

  • 使用
    上下文旋转到指定的弧度角度。旋转

  • 划清界限。这是一个棘手的部分…由于画布已经旋转,而且画布原点现在是线条的中点,因此必须
    moveTo
    减去线条长度/2和
    lineTo
    线条长度/2:
    context.moveTo(-length/2,0)
    上下文.lineTo(长度/2,0)

  • 使用
    context.Restore将上下文还原到其未旋转状态

var canvas=document.getElementById(“canvas”);
var ctx=canvas.getContext(“2d”);
var cw=画布宽度;
var ch=画布高度;
变量p1={x:75,y:75};
变量p2={x:150,y:150};
var dx=p2.x-p1.x;
变量dy=p2.y-p1.y;
变量长度=数学sqrt(dx*dx+dy*dy);
变量角度=数学常数2(dy,dx);
VarMidx=(p2.x+p1.x)/2;
var midY=(p2.y+p1.y)/2;
控制台日志(midX,midY);
绘制(角度);
请求动画帧(动画);
函数动画(时间){
请求动画帧(动画);
绘制(角度);
角度+=数学PI/30;
}
函数绘制(弧度角){
clearRect(0,0,canvas.width,canvas.height);
ctx.save();
翻译(midX,midY);
旋转(弧度角);
ctx.beginPath();
ctx.strokeStyle='red';
ctx.moveTo(-length/2,0);
ctx.lineTo(长度/2,0);
ctx.stroke();
ctx.restore();
}
body{背景色:象牙;}
画布{边框:1px纯红;}

要旋转任何内容,可以使用上下文方法-。 我们不能像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);

旋转是一种变换。你看过关于如何在绘图环境中设置转换的文档了吗?谢谢!!我不知道怎么做。你帮了很多忙。