javascript - 获取图像尺寸并将它们应用于另一个图像
问题描述
问题:我有 2 张图像,一张是从我的数据库中使用src=data:image;base64,$row[2]
并给出尺寸的。
另一张图片取自 HTML 元素,ID=img00
它是透明图片。我需要透明图像与从我的数据库中获取的图像具有相同的宽度和高度。
我的猜测:我想将 getMeta 输出保存到宽度和高度的 2 个变量中,稍后我将使用它来代替'200px'
.
你相信有比这段代码更聪明的方法吗?否则,我必须做些什么来保存 getMeta 输出并使用它而不是 200px?
function getMeta(url, callback) {
var img = new Image();
img.src = url;
img.onload = function() { callback(this.width, this.height); }
}
getMeta(
"data:image;base64,$row[2]",
function(width, height) { alert(width + 'px ' + height + 'px') }
);
var img00 = document.getElementById('img00');
if(img00 && img00.style) {
img00.style.height = '200px';
img00.style.width = '200px';
}
解决方案
如果您想使用 getMeta 内部的值,您将不得不更改最后一个代码块的执行时间。也许是这样的?
function getMeta(url, callback) {
var img = new Image();
img.src = url;
img.onload = function() { callback(this.width, this.height); }
}
function sizeImg00(w,h){
var img00 = document.getElementById('img00');
if(img00 && img00.style) {
img00.style.height = h + 'px';
img00.style.width = w + 'px';
}
}
getMeta(
"data:image;base64,$row[2]",
function(width, height) {
console.log(width + 'px ' + height + 'px');
sizeImg00(width, height);
}
);
推荐阅读
- php - 如何使通知与声音一起工作这不适用于声音甚至android中的默认通知声音
- python - 根据具有条件的其他列值创建新列
- google-sheets - 部分匹配一个范围的字符串与另一个范围的字符串,输出部分匹配
- php - 从 Laravel 中的关系中获取最后的记录
- apache-kafka - 在 Kaka Producer 中配置重试的最佳方式
- javascript - Webassembly.instantiate 期间如何定义最大内存?
- c# - 可空引用类型在具有临时可空字段的类中的使用
- memory-leaks - 如何阻止“com.newrelic.agent.Transaction”中的内存泄漏
- rest - 如何从 REST API 访问嵌套的 json?
- shell - 如何使用 Jenkins 在 Shell Script 中执行 curl 命令?