如何使用上下文在画布中旋转圆弧?

时间:2019-09-19 20:58:14

标签: javascript canvas

问题:如何使用画布上下文将弧线旋转45度?

https://codepen.io/matthewharwood/pen/bGbmOZp

const c = document.querySelector('#canvas');
const ctx = c.getContext("2d");


const {offsetWidth, offsetHeight} = c;
const x = offsetWidth/2;
const y = offsetHeight/2;
const radius = 50;
const halfRadius = radius/2;

ctx.beginPath();
ctx.arc(x - halfRadius, y - halfRadius, radius, 0, 1.5*Math.PI);
ctx.rotate(45 * Math.PI / 180);
ctx.stroke();
<canvas id="canvas" width="300" height="300">

2 个答案:

答案 0 :(得分:1)

您可以使用 ctx.save() ctx.translate(x,y)进行适当的轮换,并且不要忘记使用恢复上下文> ctx.restore()

const c = document.querySelector('#canvas');
const ctx = c.getContext("2d");


const {offsetWidth, offsetHeight} = c;
const x = offsetWidth/2;
const y = offsetHeight/2;
const radius = 50;
const halfRadius = radius/2;

ctx.beginPath();
ctx.save()
ctx.translate(x-halfRadius, y - halfRadius);
ctx.rotate(45 * Math.PI / 180 );
ctx.arc(0 , 0, radius, 0, 1.5*Math.PI);
ctx.stroke();

答案 1 :(得分:0)

您要在绘制圆弧之前旋转上下文。

const c = document.querySelector('#canvas');
const ctx = c.getContext("2d");


const {offsetWidth, offsetHeight} = c;
const x = offsetWidth/2;
const y = offsetHeight/2;
const radius = 50;
const halfRadius = radius/2;

ctx.beginPath();
ctx.rotate((Math.PI / 180) * 45);
ctx.arc(x - halfRadius, y - halfRadius, radius, 0, 1.5*Math.PI);
ctx.stroke();
<canvas id="canvas" width="300" height="300">