首页 > 解决方案 > How to rotate an arc in canvas using context?

问题描述

Question: How can I rotate my arc 45degrees using the canvas context?

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">

标签: javascriptcanvas

解决方案


you can use ctx.save() and ctx.translate(x, y) to make proper rotation and don't forget to restore the contexte with 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();


推荐阅读