Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.
Uni-app gets image information
The function of obtaining image information is not too important if it is a regular web layout, just render it.
However, if you need to complete the layout of the image information like waterfall flow, it is important to complete the height calculation before rendering the image information.
Get the picture information from UNI-app first.
function getImgInfo(imgUrl){
uni.getImageInfo({
src: imgUrl,
success: function (image) {
console.log(image.width);
console.log(image.height); }}); }Copy the code
This is the original size of the image. If used in waterfall layout, it needs to be converted according to the equal ratio of container size.
JavaScript gets the image size
After all, uni-App is based on uni-App, which may be used by a relatively small number of users. Most of the time, JavaScript is mostly used, or Vue and React frameworks are developed.
It’s time to think about how to get image information in native JavaScript.
We’re going to use a JavaScript interface called New Image() Image object.
var imgLoad = function (url, callback, context) {
var img = new Image();
img.src = url + `? timeStamp=The ${+new Date()}`;
if (img.complete) {
callback.call(context, img.width, img.height);
} else {
img.onload = function () {
callback.call(context, img.width, img.height);
img.onload = null;
};
};
};
Copy the code
Here you can see that a timestamp parameter is manually added in the image address. This is to take into account that an image may be fetched several times or read cache, adding a timestamp to ensure that the acquired image is new. If the acquired image does not need to consider this situation, you can not use it.
The above is a simple introduction of the two kinds of information to obtain pictures, the actual development can also be optimized according to the needs of processing.