canvas画五角星
时间: 2023-12-09 21:34:15 浏览: 39
以下是利用canvas绘制五角星的方法:
```html
<canvas id="myCanvas" width="200" height="200"></canvas>
```
```javascript
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
// 定义五角星10个点的坐标
var points = [
{x: 100, y: 10},
{x: 140, y: 70},
{x: 220, y: 78},
{x: 160, y: 130},
{x: 180, y: 200},
{x: 100, y: 170},
{x: 20, y: 200},
{x: 40, y: 130},
{x: -20, y: 78},
{x: 60, y: 70}
];
// 绘制五角星
ctx.beginPath();
ctx.moveTo(points[0].x, points[0].y);
for (var i = 1; i < points.length; i++) {
ctx.lineTo(points[i].x, points[i].y);
}
ctx.closePath();
ctx.fillStyle = "#FFD700";
ctx.fill();
```
相关问题
canvas绘制五角星
以下是使用canvas绘制五角星的示例代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>Canvas绘制五角星</title>
<style>
canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="200" height="200"></canvas>
<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
function drawStar(cx, cy, spikes, outerRadius, innerRadius) {
var rot = Math.PI / 2 * 3;
var x = cx;
var y = cy;
var step = Math.PI / spikes;
ctx.beginPath();
ctx.moveTo(cx, cy - outerRadius)
for (i = 0; i < spikes; i++) {
x = cx + Math.cos(rot) * outerRadius;
y = cy + Math.sin(rot) * outerRadius;
ctx.lineTo(x, y)
rot += step
x = cx + Math.cos(rot) * innerRadius;
y = cy + Math.sin(rot) * innerRadius;
ctx.lineTo(x, y)
rot += step
}
ctx.lineTo(cx, cy - outerRadius)
ctx.closePath();
ctx.lineWidth = 5;
ctx.strokeStyle = 'red';
ctx.stroke();
ctx.fillStyle = 'red';
ctx.fill();
}
drawStar(100, 100, 5, 50, 25);
</script>
</body>
</html>
```
这段代码使用了JavaScript和canvas组件来绘制一个五角星。通过调用`drawStar`函数,可以在指定的画布上绘制一个五角星。函数的参数包括五角星的中心点坐标、尖角的数量、外半径和内半径。在函数内部,使用数学运算来计算五角星的各个顶点的坐标,并使用`lineTo`方法连接这些点,最后使用`stroke`方法绘制轮廓线并使用`fill`方法填充颜色。
canvas 五角星移动
我不知道你想要的具体细节,但是以下是一个简单的canvas五角星移动的示例代码:
HTML:
```html
<canvas id="myCanvas" width="400" height="400"></canvas>
```
JavaScript:
```javascript
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
let x = 50;
let y = 50;
let speed = 2;
function drawStar(x, y, size) {
ctx.beginPath();
ctx.moveTo(x, y - size / 2);
ctx.lineTo(x + size / 3, y + size / 3);
ctx.lineTo(x - size / 2, y);
ctx.lineTo(x + size / 2, y);
ctx.lineTo(x - size / 3, y + size / 3);
ctx.closePath();
ctx.fillStyle = 'yellow';
ctx.fill();
}
function clearCanvas() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
}
function moveStar() {
clearCanvas();
drawStar(x, y, 50);
if (x + 50 >= canvas.width || x - 50 <= 0) {
speed = -speed;
}
x += speed;
requestAnimationFrame(moveStar);
}
moveStar();
```
这个示例会画一个黄色五角星,并且在canvas中从左往右移动。使用 `requestAnimationFrame` 方法来实现动画效果。移动速度可以通过更改 `speed` 变量来调整。