用canvas画转弯箭头
时间: 2023-10-23 08:14:35 浏览: 61
以下是使用 canvas 画转弯箭头的示例代码:
```html
<canvas id="arrow" width="200" height="200"></canvas>
```
```js
const canvas = document.getElementById("arrow");
const ctx = canvas.getContext("2d");
// 设置箭头样式
ctx.strokeStyle = "#000";
ctx.lineWidth = 2;
ctx.lineCap = "round";
ctx.lineJoin = "round";
// 绘制直线
ctx.beginPath();
ctx.moveTo(50, 100);
ctx.lineTo(150, 100);
ctx.stroke();
// 绘制箭头
ctx.beginPath();
ctx.moveTo(150, 100);
ctx.lineTo(130, 80);
ctx.lineTo(130, 120);
ctx.closePath();
ctx.stroke();
```
以上代码将在一个 200x200 的 canvas 中绘制一条从左到右的直线,并在直线末尾绘制一个向右的箭头。如果要画向下或向上的箭头,只需要修改箭头的坐标即可。
相关问题
用canvas画个箭头
好的,以下是代码示例:
```html
<!DOCTYPE html>
<html>
<head>
<title>Canvas Arrow</title>
<style>
canvas {
border: 1px solid #000;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="200" height="200"></canvas>
<script>
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
ctx.lineWidth = 2;
ctx.lineCap = 'round';
// 绘制箭头
function drawArrow(x, y, length, angle) {
ctx.beginPath();
ctx.moveTo(x, y);
ctx.lineTo(x + length * Math.cos(angle), y + length * Math.sin(angle));
ctx.stroke();
ctx.beginPath();
ctx.moveTo(x + length * Math.cos(angle), y + length * Math.sin(angle));
ctx.lineTo(x + length * Math.cos(angle - Math.PI / 6), y + length * Math.sin(angle - Math.PI / 6));
ctx.stroke();
ctx.beginPath();
ctx.moveTo(x + length * Math.cos(angle), y + length * Math.sin(angle));
ctx.lineTo(x + length * Math.cos(angle + Math.PI / 6), y + length * Math.sin(angle + Math.PI / 6));
ctx.stroke();
}
// 调用绘制箭头函数
drawArrow(100, 100, 80, Math.PI / 4);
</script>
</body>
</html>
```
这里使用了 canvas 的 `getContext()` 方法获取上下文对象,然后设置线条宽度和线条末端形状。接着定义了绘制箭头的函数 `drawArrow()`,该函数接收箭头起点坐标、长度和角度作为参数。在函数内部,使用 `beginPath()` 开始绘制路径,然后使用 `moveTo()` 移动到起点,使用 `lineTo()` 划线到箭头终点,最后使用 `stroke()` 绘制线条。绘制箭头头部时,使用了三次 `moveTo()` 和 `lineTo()` 组合,绘制三角形。最后调用 `drawArrow()` 函数即可在 canvas 中绘制箭头。
tkinter canvas 画箭头
在Tkinter的Canvas上绘制箭头,可以使用`create_line`方法,设置`arrow`参数为`LAST`或`BOTH`,以指示箭头的方向。下面是一个示例代码:
```python
import tkinter as tk
root = tk.Tk()
canvas = tk.Canvas(root, width=300, height=300)
canvas.pack()
# 绘制箭头
canvas.create_line(50, 50, 200, 200, arrow='last', width=2)
root.mainloop()
```
在上面的代码中,我们创建了一个Canvas对象,并使用`create_line`方法绘制了一条直线,起点坐标为(50, 50),终点坐标为(200, 200),箭头方向为最后一个点,宽度为2。你可以根据需要调整箭头的大小、颜色和位置等参数。