首页 > 解决方案 > 设置没有 src 的图像的纵横比

问题描述

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

这很好用,但是,在内存较少的速度较慢的手机上,页面上的大量数据 URL 可能会开始有点拖累。某些比例不能降低到某个点以下,从而导致画布相对较大。

有没有办法在不设置来源的情况下设置 img 元素的比例? 有没有办法将源设置为只有宽度和高度的真正空图像的格式?

编辑:下面的代码段引发错误 - iframe 限制,可能与制作图像有关。你可以在这个 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>

标签: javascripthtmlimageimage-processing

解决方案


推荐阅读