在web中使用可画实现图文混排的完整代码
时间: 2024-02-24 11:56:49 浏览: 21
以下是一个完整的图文混排的示例代码:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Canvas Demo</title>
</head>
<body>
<canvas id="myCanvas" width="600" height="400"></canvas>
<script>
// 获取canvas元素和CanvasRenderingContext2D对象
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
// 绘制矩形
ctx.fillStyle = 'red';
ctx.fillRect(50, 50, 100, 100);
// 绘制文本
ctx.fillStyle = 'white';
ctx.font = '24px Arial';
ctx.fillText('Hello World', 80, 100);
// 绘制图形
ctx.fillStyle = 'blue';
ctx.fillRect(200, 50, 100, 100);
// 创建一个新的CanvasRenderingContext2D对象
const ctx2 = canvas.getContext('2d');
// 绘制文本
ctx2.fillStyle = 'white';
ctx2.font = '24px Arial';
ctx2.fillText('This is a blue rectangle', 220, 100);
</script>
</body>
</html>
```
这个示例代码中,我们创建了一个canvas元素,并使用JavaScript绘制了两个矩形和两段文本。其中,第一段文本位于第一个矩形内部,而第二段文本位于第二个矩形上方。
需要注意的是,canvas元素上的内容是通过JavaScript动态绘制的,因此不能被搜索引擎爬取。如果需要实现SEO,可以考虑使用其他技术,例如CSS和HTML。