第 5 课 8 / 19 | 编码:L05-11
核心知识

绘制图像

海报除了自己画的图形,还可以加入已有的图片。这一页把一张“黄梅戏”图片画到画布上,并指定它的位置和大小。

<style>
body {
  font: 20px/1.5 sans-serif;
  padding: 16px;
  color: #20354e;
}
button, input, select { font: inherit; }

</style>
<canvas id="poster" width="640" height="360" style="max-width:100%;height:auto;border:1px solid #aaa">黄梅戏分享会海报</canvas>
<script>
const canvas = document.querySelector('#poster');
const ctx = canvas.getContext('2d');
const image = new Image();
image.addEventListener('load', () => {
  ctx.drawImage(image, 32, 32, 280, 280);
});
image.addEventListener('error', () => {
  console.log('图片加载失败,请检查图片路径。');
});
image.src = 'images/huangmei-opera.png';
</script>