The knowledge of pictures is divided into three parts
- HTML and CSS image processing requirements
- Js image processing
- To upload pictures
One, HTML and CSS requirements for image processing
This part, it’s all conclusive, just the conclusion.
- Image and text are vertically centered on mobile devices.
No particularly happy ending. Anyway, this has nothing to do with the picture. Why the snake? Mainly UI acceptance, UI colleagues will catch this problem to ask 😂. The problem is line-heght setting, which causes text to be off-center, and there is no particularly perfect solution. Common front end problem — Android text can’t be centered vertically
Don’t want to see the reference address, you can directly copy the face code, demo in the phone, find the best way to use, generally in 7.
Demo address Code address
Mobile demo screenshot
-
Sprite graphics, which I have mostly used in ancient times, can be configured with WebPack, but there is no need to do so.
-
Scaffolding converts small 1KB images into Base64, based on webPack configuration (scaffolding learned a foot, used gulp earlier, now abandoned).
-
Single-page frames use require or import to introduce images. CSS is not recommended.
Two, JS processing pictures
1. Base64 and image preview
Copy the following code and run directly by your demo. Slightly encapsulated when used. Typically, companies will have OCR related calls.
<html>
<head>
<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
</head>
<body>
<! -- Upload image -->
<input type="file" name="">
<! -- Image preview -->
<img src="" alt="" />
<script type="text/javascript">
const fileInput = document.querySelector('input')
fileInput.addEventListener('change'.function (e) {
const files = e.target.files
const file = files[0]
debugger
const{name, type, size} = file console.log(' file name: ${name}\n File type: ${type}\n File size: ${size} ')// The file reads the built-in object (constructor)
// https://developer.mozilla.org/zh-CN/docs/Web/API/FileReader
const reader = new FileReader()
if (file) {
/ / picture base64
reader.readAsDataURL(file)
reader.onload = function (e) {
const base64 = reader.result
console.log(`base64:${base64}`)
// // Use base64 images, preview images
// document.querySelector('img').src = base64
}
const imgEl = document.querySelector('img')
imgEl.src = createObjectURL(file)
imgEl.onload = function (e) {
const w = e.target.width
const h = e.target.height
console.log('Verifies the proportions of images by or height and width :', `${w}:${h}=${w/h}`)
}
}
}, false)
// Object URL preview image without onload event
function createObjectURL(blob) {
if (window.URL) {
return window.URL.createObjectURL(blob);
} else if (window.webkitURL) {
return window.webkitURL.createObjectURL(blob);
} else {
return null; }}</script>
</body>
</html
Copy the code
2, picture compression
It is necessary to compress images in the front end because it takes time. Another point, front-end image compression, can not specify compression storage size, this is a pit ah, do not be fooled by the product compression to 2M!
<html>
<body>
<input id="file" type="file">
<script>
var eleFile = document.querySelector('#file');
// Compress some elements and objects needed for the image
var reader = new FileReader(), img = new Image();
// Select the file object
var file = null;
// The canvas needed to scale the image
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
// Base64 after the address image is loaded
img.onload = function () {
// Image original size
var originWidth = this.width;
var originHeight = this.height;
// Maximum size limit
var maxWidth = 400, maxHeight = 400;
// Target size
var targetWidth = originWidth, targetHeight = originHeight;
// The image size exceeds the 400x400 limit
if (originWidth > maxWidth || originHeight > maxHeight) {
if (originWidth / originHeight > maxWidth / maxHeight) {
// Make it wider
targetWidth = maxWidth;
targetHeight = Math.round(maxWidth * (originHeight / originWidth));
} else {
targetHeight = maxHeight;
targetWidth = Math.round(maxHeight * (originWidth / originHeight)); }}// Canvas scales the image
canvas.width = targetWidth;
canvas.height = targetHeight;
// Clear the canvas
context.clearRect(0.0, targetWidth, targetHeight);
// Image compression
context.drawImage(img, 0.0, targetWidth, targetHeight);
// Canvas turns to blob and uploads
canvas.toBlob(function (blob) {
// Image ajax upload
var xhr = new XMLHttpRequest();
// The file was uploaded successfully
xhr.onreadystatechange = function() {
if (xhr.status == 200) {
// xhr.responseText is the returned data}};// Start uploading
xhr.open("POST".'upload.php'.true);
xhr.send(blob);
}, file.type || 'image/png');
};
// Base64 files to get the original image size
reader.onload = function(e) {
img.src = e.target.result;
};
eleFile.addEventListener('change'.function (event) {
file = event.target.files[0];
// The selected file is a picture
if (file.type.indexOf("image") = =0) { reader.readAsDataURL(file); }});</script>
</body>
Copy the code
3. Lazy loading of images
The first thing to understand about HTTP is that images that are loaded in the same session are not loaded twice. It is common to use vue-lazy with existing libraries such as VUE.
Can refer to this article implement lazy loading (the lazyload) images, this paper, a bit not, lazy loading, use a placeholder figure, such as all interface request finish loading, loading pictures again, the reason for this, is the browser’s request concurrency is limited, some figure spell request time-consuming, lead to Stalled (request latency time longer.
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
img {
display: block;
margin-bottom: 50px;
width: 400px;
height: 400px;
}
</style>
</head>
<body>
<img src="default.jpg" data-src="http://ww4.sinaimg.cn/large/006y8mN6gw1fa5obmqrmvj305k05k3yh.jpg" alt="">
<img src="default.jpg" data-src="http://ww4.sinaimg.cn/large/006y8mN6gw1fa5obmqrmvj305k05k3yh.jpg" alt="">
<img src="default.jpg" data-src="http://ww1.sinaimg.cn/large/006y8mN6gw1fa7kaed2hpj30sg0l9q54.jpg" alt="">
<img src="default.jpg" data-src="http://ww1.sinaimg.cn/large/006y8mN6gw1fa7kaed2hpj30sg0l9q54.jpg" alt="">
<img src="default.jpg" data-src="http://ww4.sinaimg.cn/large/006y8mN6gw1fa5obmqrmvj305k05k3yh.jpg" alt="">
<img src="default.jpg" data-src="http://ww4.sinaimg.cn/large/006y8mN6gw1fa5obmqrmvj305k05k3yh.jpg" alt="">
<img src="default.jpg" data-src="http://ww4.sinaimg.cn/large/006y8mN6gw1fa5obmqrmvj305k05k3yh.jpg" alt="">
<img src="default.jpg" data-src="http://ww4.sinaimg.cn/large/006y8mN6gw1fa5obmqrmvj305k05k3yh.jpg" alt="">
<img src="default.jpg" data-src="http://ww1.sinaimg.cn/large/006y8mN6gw1fa7kaed2hpj30sg0l9q54.jpg" alt="">
<img src="default.jpg" data-src="http://ww4.sinaimg.cn/large/006y8mN6gw1fa5obmqrmvj305k05k3yh.jpg" alt="">
<img src="default.jpg" data-src="http://ww4.sinaimg.cn/large/006y8mN6gw1fa5obmqrmvj305k05k3yh.jpg" alt="">
<script>
var num = document.getElementsByTagName('img').length;
var img = document.getElementsByTagName("img");
var n = 0; // Store the location where the image is loaded to avoid traversing from the first image every time
lazyload(); // when the page is loaded, the image in the area is loaded
window.onscroll = lazyload;
function lazyload() { // Listen for page scroll events
var seeHeight = document.documentElement.clientHeight; // Height of visible area
var scrollTop = document.documentElement.scrollTop || document.body.scrollTop; // Height of scroll bar from top
for (var i = n; i < num; i++) {
if (img[i].offsetTop < seeHeight + scrollTop) {
if (img[i].getAttribute("src") = ="default.jpg") {
img[i].src = img[i].getAttribute("data-src");
}
n = i + 1; }}}</script>
</body>
Copy the code
4. Image preloading
To be continued…
Upload pictures
This is to upload images using the FETCH API and Axios.
Fetch uploads images
const fileBtn = document.getElementById('file')
const userName = document.getElementById('userName')
fileBtn.addEventListener('change', () = > {const fd = new FormData()
fd.append('file', fileBtn.files[0])
fd.append('userName', userName.value)
fd.append('age'.'18')
fetch('http://localhost:3036/upload', {
method: 'POST'.body: fd,
// headers: {
// 'Content-Type': 'multipart/form-data'
// }
}).then(res= > {
if(res.ok) {
console.log('success')
return res.json();
} else {
console.log('Network error')
}
}).then(res= > {
console.log('res is',res); })})Copy the code
Axios uploads images
import axios from 'axios'
var file = document.getElementById("upload_file").files[0]; var formdata1=new FormData(); // Create the form object formData1.append ('img',file,file.name); Formdata1.append (formData1.append (formData1.append (formData1.append))'img',file);
let config = {
headers:{'Content-Type':'multipart/form-data'}}; // Add the request header axios.post('/xapi/upimage', formData1,config). Then (response)=>{// here /xapi/upimage is the interface console.log(response.data); })Copy the code
conclusion
This article is the front-end foundation, many problems are solved by the conclusion, encountered twice know how to solve, there is no special good difficult to understand the place. If you don’t understand, run the code again to know the backend interface for uploading images, know a little about PHP or NodeJS, and develop a simple service.