canvas画个半圆往左是负数往右是正数
时间: 2023-08-10 12:12:14 浏览: 51
好的,以下是一个简单的示例代码,可以绘制一个半圆,并根据鼠标位置确定半圆的方向(向左或向右):
```html
<canvas id="myCanvas" width="400" height="200"></canvas>
<script>
// 获取 canvas 元素和上下文对象
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
// 定义半径和起始角度
var radius = 80;
var startAngle = Math.PI;
// 监听鼠标移动事件
canvas.addEventListener("mousemove", function(event) {
// 获取鼠标在 canvas 中的相对位置
var mouseX = event.clientX - canvas.offsetLeft;
var mouseY = event.clientY - canvas.offsetTop;
// 根据鼠标位置确定半圆的方向
var direction = mouseX > canvas.width / 2 ? 1 : -1;
// 清空画布
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 绘制半圆
ctx.beginPath();
ctx.arc(canvas.width / 2, canvas.height / 2, radius, startAngle, startAngle + direction * Math.PI, direction == 1);
ctx.stroke();
});
</script>
```
解释一下代码:
1. 首先获取 canvas 元素和绘图上下文对象。
2. 定义半径和起始角度。
3. 监听 canvas 的鼠标移动事件,获取鼠标在 canvas 中的相对位置。
4. 根据鼠标位置确定半圆的方向:如果鼠标在 canvas 右侧,则方向为 1(向右),否则为 -1(向左)。
5. 清空画布。
6. 绘制半圆:使用 `ctx.arc` 方法绘制半圆,其中圆心位置为 canvas 的中心,半径为上面定义的 radius,起始角度为 startAngle,终止角度为 startAngle + direction * Math.PI(如果方向为 1,则终止角度为 startAngle + Math.PI,否则为 startAngle - Math.PI),最后一个参数表示是否顺时针绘制(如果方向为 1,则为 true,否则为 false)。
7. 使用 `ctx.stroke` 方法绘制半圆的边框。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)