帮我用 canvas 制作一个顶牌,要求:顶部矩形带边框放文字,矩形底部中间是垂线
时间: 2023-08-11 19:51:46 浏览: 34
好的,以下是一个简单的实现方式:
```html
<canvas id="myCanvas" width="200" height="150"></canvas>
```
```javascript
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
// 顶部矩形
ctx.fillStyle = "#fff";
ctx.fillRect(0, 0, canvas.width, 50);
ctx.strokeStyle = "#000";
ctx.strokeRect(0, 0, canvas.width, 50);
// 文字
ctx.fillStyle = "#000";
ctx.font = "24px Arial";
ctx.textAlign = "center";
ctx.fillText("顶牌", canvas.width / 2, 30);
// 垂线
ctx.beginPath();
ctx.moveTo(canvas.width / 2, 50);
ctx.lineTo(canvas.width / 2, canvas.height);
ctx.strokeStyle = "#000";
ctx.stroke();
```
效果图如下:
![顶牌](https://img-blog.csdnimg.cn/20210626101210925.png)
相关问题
帮我用 canvas 制作一个顶牌,要求:顶部矩形带边框放文字,且矩形背景是一张图片。矩形底部中间是垂线
好的,以下是使用 canvas 制作顶牌的代码。请注意,这里的矩形背景图片需要先加载完成才能绘制,所以我们需要在图片加载完成后再进行绘制操作。
```html
<canvas id="myCanvas" width="200" height="100"></canvas>
```
```javascript
// 获取 canvas 元素和上下文
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
// 创建新的图片对象
var bgImg = new Image();
bgImg.src = "your_image_url";
// 监听图片加载完成事件,加载完成后绘制顶牌
bgImg.onload = function() {
// 绘制矩形背景图片
ctx.drawImage(bgImg, 0, 0, 200, 100);
// 绘制顶部矩形带边框和文字
ctx.fillStyle = "#ffffff";
ctx.fillRect(10, 10, 180, 30);
ctx.strokeStyle = "#000000";
ctx.lineWidth = 2;
ctx.strokeRect(10, 10, 180, 30);
ctx.font = "16px Arial";
ctx.fillStyle = "#000000";
ctx.textAlign = "center";
ctx.fillText("顶部文字", 100, 30);
// 绘制矩形底部中间的垂线
ctx.strokeStyle = "#000000";
ctx.lineWidth = 2;
ctx.beginPath();
ctx.moveTo(100, 70);
ctx.lineTo(100, 90);
ctx.stroke();
}
```
其中,`your_image_url`需要替换成您自己的矩形背景图片链接。
您也可以根据需要调整顶牌的大小、位置、颜色等属性。
帮我用canvas绘制一个顶牌
以下是使用Canvas绘制一个顶牌的示例代码:
```javascript
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
// 顶点坐标
var vertices = [
{ x: 50, y: 50 },
{ x: 50, y: 150 },
{ x: 150, y: 150 },
{ x: 150, y: 50 },
{ x: 100, y: 100 }
];
// 边界坐标
var bounds = {
left: vertices[0].x,
top: vertices[0].y,
right: vertices[0].x,
bottom: vertices[0].y
};
// 计算边界坐标
for (var i = 1; i < vertices.length; i++) {
var vertex = vertices[i];
if (vertex.x < bounds.left) bounds.left = vertex.x;
if (vertex.y < bounds.top) bounds.top = vertex.y;
if (vertex.x > bounds.right) bounds.right = vertex.x;
if (vertex.y > bounds.bottom) bounds.bottom = vertex.y;
}
// 绘制多边形
ctx.beginPath();
ctx.moveTo(vertices[0].x, vertices[0].y);
for (var i = 1; i < vertices.length; i++) {
ctx.lineTo(vertices[i].x, vertices[i].y);
}
ctx.closePath();
ctx.fillStyle = '#ff0000';
ctx.fill();
// 绘制边界矩形
ctx.beginPath();
ctx.rect(bounds.left, bounds.top, bounds.right - bounds.left, bounds.bottom - bounds.top);
ctx.strokeStyle = '#0000ff';
ctx.lineWidth = 2;
ctx.stroke();
```
这个代码使用了Canvas的绘图API,首先定义了一个包含顶点坐标的数组,然后计算出顶点形成的多边形的边界坐标,最后使用绘图API绘制多边形和边界矩形。你可以将这段代码复制到一个HTML文件中,并在浏览器中打开该文件,就可以看到绘制出来的顶牌了。