上节课跟大家讲解了基本的线条和多边形的绘制,主要的方法是stroke()和fill()方法。并且还封装了两个动态绘制线条和多边形的方法。这节课我们带领大家来认识一下文字以及图片的绘制,从而理解一下canvas的像素操作。
首先我们来说文字的绘制,文字的绘制用到关键方法叫做fillText(),当然如果你绘制的是空心文字那可以使用strokeText(),如果给文字设置颜色还是用到对应的fillStyle和strokeStyle,废话不多说我们直接来看代码。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>文字与图片测试</title>
</head>
<body>
<canvas width="500px" height="500px"></canvas>
<script>
const canvas=document.querySelector('canvas');
const ctx=canvas.getContext('2d')
ctx.fillStyle="red"
ctx.fillText('你好世界!'