第 5 课 15 / 19 | 编码:L05-21
比较与审查

先画背景还是先写标题?

分别运行 A、B,比较标题能否显示。两段代码使用相同的不透明背景色和默认叠加方式,只交换了背景与文字的绘制顺序。

写法 A

<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');
ctx.fillStyle = 'white';
ctx.fillText('分享会', 30, 60);
ctx.fillStyle = 'navy';
ctx.fillRect(0, 0, 300, 150);
</script>

写法 B

<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');
ctx.fillStyle = 'navy';
ctx.fillRect(0, 0, 300, 150);
ctx.fillStyle = 'white';
ctx.fillText('分享会', 30, 60);
</script>