When making some activity pages, there are often needs to upload pictures, and the pictures, generated text and stickers also need to be generated into a card that users can long-press to save. This requirement has been completed once before, and it was met again recently. It was all implemented using canvas. Just put together a blog. If there is a better implementation method, you are welcome to discuss it together.
Use canvas to compress imagesWhen using the write input tag in html and the type is file, you can call up the photo album of your phone to select photos, and you can also support the camera to take photos. In this scenario, the size of the image may be larger and may exceed the maximum range supported by the backend, causing the upload to fail.
<input id=file type=file>
1. First get the image file
var eleFile = document.querySelector('#file'); var reader = new FileReader() eleFile.addEventListener('change', function (event) { file = event.target.files[0]; console.log(file) // The selected file is an image if (file.type.indexOf(image) == 0) { reader.readAsDataURL(file); } });2. Now that you have obtained the image file, you have to understand the use of the FileReader object in js.
FileReader objects allow web applications to asynchronously read the contents of a file (or raw data buffer) stored on the user's computer
method:
| method name | parameter | describe |
|---|---|---|
| abort | none | Interrupt reading |
| readAsBinaryString | file | binary code |
| readAsDataURL | file | Read file as DataURL |
| readAsText | file, [encoding] | Read file as text |
| event | describe |
|---|---|
| onabort | Triggered on interrupt |
| onerror | onabort |
| onload | Triggered when file read completes successfully |
| onloadend | Triggered by read completion, regardless of success or failure |
| onloadstart | Fires when reading starts |
| onprogress | Reading |
Continue the above operation. After getting the picture, you need to process and convert the file. At this time
var reader = new FileReader(); //Read the file into the page in the form of Data URL reader.readAsDataURL(file); reader.onload=function(e) { console.log(reader) }Now that the image has been retrieved and converted, it can now be compressed.
var eleFile = document.querySelector('#file'); var reader = new FileReader() eleFile.addEventListener('change', function (event) { file = event.target.files[0]; // console.log( file) // The selected file is an image if (file.type.indexOf(image) == 0) { var reader = new FileReader(); // Convert the file to Data Read the page in the form of URL reader.readAsDataURL(file); reader.onload=function(e) { // console.log(this.result) var pre=document.getElementById(pre); pre.setAttribute(src, this.result ) canvasDataURL(this.result, 100, 0.5) } } }) /* [canvasDataURL compressed by canvas] * @params path The base64 format of the image* @params targetWidth The width of the compressed image* @params quality The smaller the image quality value, the blurr the drawn image*/ function canvasDataURL(path, targetWidth, quality) { var img = new Image(); img.src = path img.onload = function () { // var that = this // console.log(that) // Default proportional compression var w = this.width var h = this.height scale = w / h; w = targetWidth h = targetWidth / scale var quality = quality; // The default image quality is 0.7 // Generate canvas var canvas = document.createElement('canvas'); var ctx = canvas.getContext('2d'); // Create attribute node var anw = document.createAttribute(width); anw.nodeValue = w; var anh = document.createAttribute(height); anh.nodeValue = h; canvas.setAttributeNode(anw); canvas.setAttributeNode(anh); ctx.drawImage(this, 0, 0, w, h); // The smaller the quality value, the better The more blurry the drawn image is var base64 = canvas.toDataURL('image/jpeg', quality); var result=document.getElementById(result); result.setAttribute(src, base64) } }It's very simple, so you can get the compressed image. From the above code, we can know that the principle is that the toDataURL method in canvas can specify the format and compression quality of the compressed image, and compress the canvas information and convert it to base64 encoding. compression.
Make cards using canvasScene: Combine the just compressed picture with another picture, long press to save.
function drawCanvas (target) { var canvas = document.querySelector('#myCanvas') var ctx = canvas.getContext('2d') // It is the physical pixels on the device and device-independent pixels (dips) Ratio var dp = window.devicePixelRatio || 1 var backingStoreRatio = ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backingStorePixelRatio || 1 var ratio = this.dp / this.backingStoreRatio var oldWidth = canvas.width var oldHeight = canvas.height canvas.width = oldWidth * ratio canvas.height = oldHeight * ratio canvas.style.width = oldWidth + 'px' canvas.style.height = oldHeight + 'px' ctx.scale(ratio, ratio) var headerImg = new Image() var bgImg = new Image() headerImg.src = target bgImg.src = '../bg.png' headerImg.onload = (e) => { // Aspect ratio of the picture var rate = headerImg.width / headerImg.height console.log(rate) bgImg.onload = (e) => { ctx.drawImage(headerImg, 10, 30, 50, (50 / rate )) // Background image ctx.drawImage(bgImg, 0, 0, 150, 150) ctx.fillText('Awesome', 80, 70) var resultImg = new Image() resultImg.src = canvas.toDataURL('image/png', 1) resultImg.style.width = '100%' var cardImg=document .getElementById(cardImg); cardImg.setAttribute(src, resultImg.src) } }Get the image you just obtained, and after the image is loaded, draw it on the canvas. You can also add text, etc. Finally, the canvas information is converted to base64 encoding for implementation. Examples can be practiced through code
The above is the entire content of this article. I hope it will be helpful to everyone’s study. I also hope everyone will support VeVb Wulin Network.