javascript - 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">
解决方案
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();
推荐阅读
- javascript - HTML 按钮元素的 value 属性的确切用途是什么?
- cmake - 自定义构建命令不适用于“货物发布”,因为 CMake 表示路径将超过 CMAKE_OBJECT_PATH_MAX
- amazon-web-services - 将子域路由到 AWS api 网关
- python - 在python中将参数更改为布尔值
- stm32 - 在 STM32F1 上使用 SPI 和 DMA 的问题
- javascript - 快速路由的自定义中间件
- sql - SQL - 如何使用键值保存数据
- ios - 我的 UIView 的屏幕截图并将其保存为图像或 PDF Swift 5、Xcode 13、iPad
- vue.js - 2020年全球如何将scss文件添加到Vue项目
- android - Firebase 查询 startAt() 不返回任何值?