我使用动态创建的图像来保持具有固定高度的盒子的纵横比 . 图像源设置为从具有给定宽度和高度的画布提供的数据URL,然后将图像附加到div,其可以包含任何内容,具有任何高度,并且仍然保持固定的宽高比 .

这种情况很好,但是,对于内存较少的较慢的手机,页面上的大量数据网页可能会开始有点拖累 . 一些比率不能降低到某一点以下,导致相对较大的画布 .

Is there any way to set the ratio of an img element without setting its source? 有没有办法将源设置为只有宽度和高度的真正空图像的格式?

编辑:下面的代码片段引发错误 - iframe限制,可能与制作图像有关 . 您可以在this CodePen看到无错误版本 .

const wrapper = document.querySelector(".wrapper");

function addRatioBox(width, height = 1) {
	const cvs = document.createElement("canvas");
	
	const img = new Image(width, height);
	const box = document.createElement("div");
	
	cvs.width = width;
	cvs.height = height;
	
	img.src = cvs.toDataURL("image/png");
	
	box.appendChild(img);
	box.className = "ratioBox";
	
	wrapper.appendChild(box);
}

addRatioBox(1);
addRatioBox(4, 3);
addRatioBox(16, 9);
addRatioBox(2, 1);
.ratioBox {
  background: orange;
  display: inline-block;
  height: 100%;
  margin-right: 10px;
}

.ratioBox img {
  height: 100%;
  width: auto;
  display: block;
}




/* just a whole bunch of stuff to make things prettier from here on down */

.wrapper {
  background: #556;
  padding: 10px;
  position: absolute;
  height: 20%;
  top: 50%;
  left: 50%;
  white-space: nowrap;
  transform: translate(-50%, -50%);
}

body {
  background: #334;
}

.ratioBox:last-of-type {
  margin-right: 0;
}
<div class="wrapper"></div>