Home >Web Front-end >H5 Tutorial >Code example for compressing images using canvas
The content of this article is about the code example of compressing images on canvas. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
// 对图片进行压缩 function compress(imgPath) { var image = new Image(); //新建一个img标签(还没嵌入DOM节点) image.src = imgPath; image.onload = function() { var canvas = document.createElement('canvas'); var context = canvas.getContext('2d'); var imageWidth = image.width / 3; //压缩后图片的大小 var imageHeight = image.height / 3; var data = ''; canvas.width = imageWidth; canvas.height = imageHeight; context.drawImage(image, 0, 0, imageWidth, imageHeight); data = canvas.toDataURL('image/jpeg') //压缩完成 $(".srcDiscernImg").attr("src", data); console.log("渲染。。。。"); } }
This article has ended here. For more exciting content, you can pay attention to the HTML5 Video Tutorial column on the PHP Chinese website! ! !
The above is the detailed content of Code example for compressing images using canvas. For more information, please follow other related articles on the PHP Chinese website!