根据浏览器宽度和高度在 canvas 内缩放图像

scaling image inside canvas according to browser width and height

我有一个 canvas,里面有一张图片 it.Let 说它的宽度为 800px,高度为 520px。 我应该如何根据浏览器的高度和宽度缩放 canvas 绘制的图像,以便我可以在任何浏览器尺寸下看到正确的图像?

谢谢

尚未对此进行测试,但您可以像 android 开发指定其分辨率处理那样进行。假设您的参考分辨率(1x 修改)是 1920x1080 并且您有该尺寸的固定分辨率(您提到的 800x520)。然后您可以将这些值与其他分辨率的修改因子相乘:

<canvas id="myCanvas"></canvas>
<script>
  var canvas = document.getElementById('myCanvas');
  var context = canvas.getContext('2d');
  var x = 0; //x coordinate of the picture
  var y = 0; //y coordinate of the picture
  var screenWidth = window.innerWidth || document.body.clientWidth;
  var screenHeight = window.innerHeight || document.body.clientHeight;
  var multiplication = ((screenWidth / 1920) + (screenHeight / 1080)) / 2;
  var width = 800 * multiplication;
  var height = 520 * multiplication;
  var imageObj = new Image();
  imageObj.onload = function() {
    context.drawImage(imageObj, x, y, width, height);
  };
  imageObj.src = '[your source here]';
</script>

这里的陷阱是如果 window 大小没有相同的纵横比 (16:9)。如您所见,倍增因子取宽度与 1920 值以及高度与 1080 值之间的相对比率的平均值。还要确保在客户端 window 调整大小时刷新 canvas,尽管浏览器应该自行处理(它会重绘)。