跳到主要内容

HTMLCanvasElement 实例方法与属性

· 阅读需 4 分钟
Uf8uwA

画布尺寸

Canvas 有两种 widthheight

  1. 一种是 width、height 属性,一般称其为 画布尺寸,即图形绘制的地方。默认值分别为 300px、150px。

例如:

<canvas id="canvas" width="300" height="150"></canvas>
  1. 另一种是 CSS 样式里的 width、height 属性,可通过内联样式、内部样式表或外部样式表设置。一般称其为 画板尺寸,用于渲染绘制完成的图形。默认值为空。

例如:

<canvas id="canvas" style="width: 300px; height: 150px;"></canvas>

<style>
#canvas {
width: 300px;
height: 150px;
}
</style>
画布尺寸画板尺寸说明
已设置未设置画板尺寸随画布尺寸改变
未设置已设置画板尺寸将不再随画布尺寸而改变
已设置已设置画板尺寸将不再随画布尺寸而改变

如果两者设置的尺寸不一样时,就会产生一个问题,渲染时画布要通过缩放来使其与画板尺寸一样,那么画布上已经绘制好的图形也会随之缩放,随之导致变形失真。

下面为绘制从原点到 200*200 的直线:

实时编辑器
class Demo extends React.Component {
  componentDidMount() {
    const canvasList = document.querySelectorAll('.canvas');

    canvasList.forEach(item => {
      const context = item.getContext('2d');

      this.renderPath(context);
    });
  }

  renderPath(ctx) {
    ctx.beginPath();
    ctx.moveTo(0, 0);
    ctx.lineTo(200, 200);
    ctx.stroke();
  }

  render() {
    return (
      <>
        <p>1、已设置画布宽高属性(200px * 200px),未设置画板样式宽高,画板尺寸随画布尺寸改变</p>
        <canvas id="canvas1" className="canvas" width="200" height="200"></canvas>
        <p>2、未设置画布宽高属性,但已设置画板样式宽高(200px * 200px)</p>
        <canvas id="canvas2" className="canvas" style={{ width: 200, height: 200 }}></canvas>
        <p>3、设置画布宽高属性(300 * 300),设置画板样式宽高(200 * 200)</p>
        <canvas
          id="canvas3"
          className="canvas"
          width="300"
          height="300"
          style={{ width: 200, height: 200, border: '1px solid #000' }}></canvas>
        <p>4、设置画布宽高属性(200 * 200),设置画板样式宽高(300 * 300)</p>
        <canvas
          id="canvas4"
          className="canvas"
          width="200"
          height="200"
          style={{ width: 300, height: 300, border: '1px solid #000' }}></canvas>
      </>
    );
  }
}
结果
Loading...

其他例子:

<body>
<canvas id="myCanvas">一旦浏览器不兼容canvas,会默认渲染内部结构 浏览器不支持canvas</canvas>
<script>
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
// 尺寸一直是固定的
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

// 浏览器尺寸一旦变化,画布也变化
canvas.style.width = window.innerWidth;
canvas.style.height = window.innerHeight;
// 设置文本样式
ctx.font = '30px Arial';
ctx.fillStyle = 'red';

// 在Canvas上绘制文本
ctx.fillText('Hello, World!', canvas.width / 2, canvas.height / 2);
</script>
</body>

References

  1. Mozilla: HTMLCanvasElement
  2. Visualization Guidebook: canvas basic by tsejx
  3. canvas 绘制“飞机大战”小游戏,真香!by HarmonyOS 开发者技术
  4. 前端可视化入门与实战