canvas compressed pictures are converted into base64 format output file stream
- 2021-08-03 08:33:01
- OfStack
Yesterday, I studied the method of compressing pictures under canvas, and uploaded it to everyone to share it under 1
<!-- Call canvas Method -->
<canvas id="canvas"></canvas>
<!-- Compressed picture road strength -->
<img src="" class="preview">
<img src="" class="preview">
<!-- Original image compression -->
<img class="source" src="" style="display: none;">
<img class="source" src="" style="display: none;">
// drawimage3 Kinds of calling methods
// ctx.drawImage(Image,dx,dy);
// ctx.drawImage(Image,dx,dy,dWidth,dHeight);
// ctx.drawImage(Image,sx,sy,sWidth,sHeight,dx,dy,dWidth,dHeight);
//images Picture elements, out of the pre-judgment also support other 3 Format, which are htmlvideoElement htmlcanvasElement imagebitmap
//todataurl Yes canvas Method of canvas element , Object in the specified picture format data url, That is base64 Coded string
//todataurl Method accepts up to two parameters, both of which are optional:
//type Picture format . Support 3 A kind of way , They are image/jpeg images/png image/webp, The default is image.png
var canvas = document.getElementById('canvas');
var source = document.getElementsByClassName('source');
var preview = document.getElementsByClassName('preview');
canvas.style.display = "none";
window.onload = function() {
// Multiple pictures circulate to facilitate compression
for(var i = 0; i < preview.length; i++) {
var width = source[i].width;
var height = source[i].height;
var context = canvas.getContext('2d');
//sx To draw to canvas The source picture area of the canvas (rectangle) is in the x Offset on axis
var sx = 0;
//sy To draw to canvas The source picture area of the canvas (rectangle) is in the y Offset on axis
var sy = 0;
//swidth To draw to canvas The width of the source picture area in the canvas, or if this value is not specified, the width is sx Distance to the rightmost side of the picture
var sWidth = width;
//sHeight The width of the source image area to draw into the canvas. If this value is not specified, the height is sy Distance to the bottom of the picture
var sHeight = height;
//dx The upper left corner of the source picture is in canvas On the canvas x Offset on axis
var dx = 0;
//dy The upper left corner of the source picture is on the canvas y Offset on axis
var dy = 0;
//dwidth To draw a picture canvas Canvas width
//dHeight Canvas height for drawing pictures
var dWidth = width;
var dHeight = height;
var quality = 0.2;
canvas.width = width;
canvas.height = height;
context.drawImage(source[i], sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight);
var dataUrl = canvas.toDataURL('image/jpeg', quality);
preview[i].src = dataUrl;
}
// console.info(dataUrl);
};
// Traverse the original image
for(var i = 0; i < source.length; i++) {
source[i].src = 'img/' + (i + 1) + '.jpg';
}