gpt4 book ai didi

javascript - HTML Canvas - 从特定点旋转一条线

转载 作者:行者123 更新时间:2023-12-03 01:31:32 27 4
gpt4 key购买 nike

我在 HTML Canvas 上的特定点 (250,250) 处旋转线条时遇到问题,我想知道人们是如何做到的。我查看了其他答案并尝试了它们,但它们没有解决我的问题。

var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");

function circles(){

context.beginPath();
context.arc(250,250,6.35,0,2*Math.PI);
context.stroke();

}

function lines(){
var deg = 45;
context.beginPath();
context.moveTo(250,250);
context.lineTo(250,0);
context.stroke();

context.save();
context.rotate(deg * Math.PI / 180);
context.translate(20,-25);

// This is the line I want to rotate
context.beginPath();
context.moveTo(250,250);
context.lineTo(250,0);
context.stroke();

//

context.restore();

context.beginPath();
context.moveTo(0,250);
context.lineTo(500,250);
context.stroke();

}

circles();
lines();

https://jsfiddle.net/athkcLyr/1/

最佳答案

有了上面的代码,您就快完成了。关键是,在调用rotate之前,您需要将上下文翻译到您想要旋转的点。您还需要在最后翻译上下文。

下面带有注释的示例:

var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");

function circles(){
context.beginPath();
context.arc(250,250,225.5,0,2*Math.PI);
context.stroke();

context.beginPath();
context.arc(250,250,170,0,2*Math.PI);
context.stroke();

context.beginPath();
context.arc(250,250,162,0,2*Math.PI);
context.stroke();

context.beginPath();
context.arc(250,250,107,0,2*Math.PI);
context.stroke();

context.beginPath();
context.arc(250,250,99,0,2*Math.PI);
context.stroke();

context.beginPath();
context.arc(250,250,16,0,2*Math.PI);
context.stroke();

context.beginPath();
context.arc(250,250,6.35,0,2*Math.PI);
context.stroke();
}

function lines(){
var deg = 45;
context.beginPath();
context.moveTo(250,250);
context.lineTo(250,0);
context.stroke();

context.save();
// Translate the context to the point we want to rotate around
context.translate(250, 250);
// Perform the rotation
context.rotate(deg * Math.PI / 180);

// Draw the line
context.beginPath();
context.moveTo(0,0);
context.lineTo(-250,0);
context.stroke();

// Translate the context back to it's original position
context.translate(-250, -250);
context.restore();

context.beginPath();
context.moveTo(0,250);
context.lineTo(500,250);
context.stroke();

}

//Reference Lines
function refLines(){
context.beginPath();
context.moveTo(0,250);
context.lineTo(500,250);
context.stroke();

context.beginPath();
context.moveTo(250,0);
context.lineTo(250,500);
context.stroke();

context.beginPath();
context.moveTo(0,0);
context.lineTo(500,500);
context.stroke();

context.beginPath();
context.moveTo(0,500);
context.lineTo(500,0);
context.stroke();
}

circles();
lines();
section{
text-align: center;
margin: auto;
}

canvas{
border: 1px solid black;
}
<canvas id="canvas" width="500" height="500"></canvas>

关于javascript - HTML Canvas - 从特定点旋转一条线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51275028/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com