Home >Web Front-end >HTML Tutorial >Specific steps to use canvas to compress images
Steps to use canvas to compress images:
(Recommended video tutorial: html video tutorial)
1. Get Picture element
2. Draw a blank canvas
3. Draw the picture on the canvas
4. Convert the canvas to base64 (the method called here can achieve compression , base64 can be directly put into src or passed to the backend, converted to other formats for transmission, etc.)
Code implementation:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <img src="test.png" style="max-width:90%" id="imgBefore" alt="Specific steps to use canvas to compress images" > <img src="" id="imgafter" alt="Specific steps to use canvas to compress images" > //待会压缩完的图片放入这里。 </body> </html> <script> var img = document.getElementById('imgBefore') //拿到图片元素 img.setAttribute("crossOrigin",'Anonymous') //这句话并不是必要的,如果你的图片是一个网络链接, //那么canvas绘制时可能会报错,是因为跨域的安全性问题。报错时加上就对了。 img.onload = ()=>{ //要确保图片已经加载完才进行绘制,不然拿不到图片元素会绘制出全黑的区域,就是失败。 var width = img.width var height = img.height var canvas = document.createElement('canvas'); var ctx = canvas.getContext('2d'); canvas.width = width; canvas.height = height; //以上几步都在绘制一个canvas ctx.drawImage(img,0,0,width,height);//将图片绘制进去,这里第一个参数可以接受很多格式, //以元素为例子,详情https://developer.mozilla.org/zh-CN/docs/Web/API/CanvasRenderingContext2D/drawImage var base64 = canvas.toDataURL('image/jpeg',0.2); //第二个参数为压缩的比例,越小越模糊。0-1 document.getElementById('imgafter').src = base64 } </script>
Effect comparison:
Before compression
After compression:
Related recommendations: html tutorial
The above is the detailed content of Specific steps to use canvas to compress images. For more information, please follow other related articles on the PHP Chinese website!