Home > Web Front-end > H5 Tutorial > body text

Code example for compressing images using canvas

不言
Release: 2019-04-11 13:50:13
forward
2853 people have browsed it

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("渲染。。。。");
        }
    }
Copy after login

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!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template