显示图片

使用 Canvas 显示图片,将图片的尺寸适配 Canvas 容器的尺寸来居中显示。

1

我是将图片先用 base64 编码后再用 Canvas 显示。

图片的 base64 文件

<div id="canvasContainer" style="width:100%;text-align:center;overflow:auto">
  <canvas id="canvas" width="1" height="1" tabindex="1">
    Sorry, your browser does not support HTML5 Canvas functionality which is
    required for this application.
  </canvas>
</div>
const canvasContainer = document.getElementById("canvasContainer");
const canvas = document.getElementById("canvas");
const context = canvas.getContext("2d");

if (canvasContainer && canvas) {
  if (context) {
    const img = new Image();
    img.src = imageData; // 图片base64后的string
    img.onload = () => {
      // 计算图片的缩放比例
      // 使用原尺寸高度,在默认状态下会出现上下滚动条
      const heightScaleRate = (canvasContainer.offsetHeight - 5) / img.height;
      const widthScaleRate = (canvasContainer.offsetWidth - 5) / img.width;
      // 选取比率小的,以防超过边界出现滚动条
      const scaleRate =
        heightScaleRate > widthScaleRate ? widthScaleRate : heightScaleRate;
      context.scale(scaleRate, scaleRate);

      canvas.width = Math.round(img.width * scaleRate);
      canvas.height = Math.round(img.height * scaleRate);

      context.beginPath();
      context.drawImage(img, 0, 0, canvas.width, canvas.height);
      context.stroke();
    };
  }
}