javascript - 设置没有 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>
解决方案
推荐阅读
- vba - Visual Basic 主题
- android - 更高 Api 级别的 SharedPreferences 不起作用?
- android - 在 android studio 中分离 HEAD
- django - Django 使用完全相同的查询进行多对多过滤
- java - JVM 不会在 OnOutOfMemoryError 上被杀死
- apache-kafka - Apache kafka 代理消费消息给其他人
- h3 - H3Index 是有序的吗?
- angular - stroke-dasharray 不能与 Angular 6 绑定
- python - 将 DataFrame B 中的所有行加入 DataFrame A pandas 中的每一行,将索引合并到多索引中
- c - 从 Tcl_HashTable 检索对象以销毁对象的问题