Sample code for Canvas and image compression

小云云
Release: 2023-03-17 19:24:01
Original
1455 people have browsed it

The canvas element is used to draw graphics on web pages. HTML5's canvas element uses JavaScript to draw 2D images on a web page. On the canvas of the rectangular area, JavaScript draws 2D graphics and renders them pixel by pixel. The canvas element can be used in various ways to draw paths, rectangles, circles, characters, and add images. In this article, we share with you the sample code of Canvas and image compression.

Canvas image compression process

Next, I will explain the specific process of Canvas image compression with specific examples.

1. Local image input

1. Get local file

<!--HTML-->
<input type="file" id="choose-img" />
Copy after login

// JS
var chooseImg = document.getElementById("choose-img");
chooseImg.onchange = function(e){
    var file = this.files[0];
    // ……  (省略部分代码后续依次展示,下同)
};
Copy after login

It's very simple, just get the local file through the button with type file.

2. Determine the type of local file obtained

<!--HTML-->
<p id="result"></p>
Copy after login

// JS
var result = document.getElementById("result");    // 用于显示图片输出结果,或者错误提示
if(/image/.test(file.type)){     // 判断文件类型是否为图片
    // ……
}
else{
    result.innerHTML = &#39;<span style="color: red;">文件类型有误!</span>&#39;;
}
Copy after login

3. Output the obtained local image in base64 format

var img = new Image(),      // 创建图片对象,用于放置原始图片
    reader = new FileReader();
reader.readAsDataURL(file);    // 以base64格式读取并存入FileReader对象的result属性中
reader.onload = function(){
    img.src = this.result;   // 将图片base64字符串直接赋予Image对象的src中
    document.body.insertBefore(img,chooseImg);   // 将输出的图片插入到文件按钮之前
    img.onload = function(){
        // ……
    };
};
Copy after login

2. Draw in Canvas Picture

1. Create canvas

var canvas = document.createElement(&#39;canvas&#39;);
canvas.width = img.clientWidth;
canvas.height = img.clientHeight;
var context = canvas.getContext(&#39;2d&#39;);
Copy after login

Note: The canvas size is the same as the width and height of the entered picture .

2. Draw the picture

context.drawImage(img,0,0,canvas.width,canvas.height);
Copy after login

3. Compress the picture and output

<!--HTML-->
图片压缩比率 : <input id="rate" type="number" min="0" max="100" /> %
Copy after login

// JS
var rate = document.getElementById("rate").value || 100;   // 输入图片压缩比率,默认为100%
var imgUrl = canvas.toDataURL(file.type,rate/100);   // 第一个参数为输出图片类型,第二个为压缩比
result.innerHTML = &#39;压缩后:<img src="&#39;+ imgUrl +&#39;" />&#39;;     // 将压缩后的图片置于result中显示
img.style.display = &#39;none&#39;;   // 将原始图片隐藏
Copy after login

Output the picture drawn in the Canvas canvas in base64 format again.

4. Complete code display

<!--HTML-->
图片压缩比率 : <input id="rate" type="number" min="0" max="100" /> %

Copy after login

// JS
var chooseImg = document.getElementById("choose-img"),
    result = document.getElementById("result");
chooseImg.onchange = function(e){
    var file = this.files[0];
    if(/image/.test(file.type)){
        var img = new Image(),
            reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = function(){
            img.src = this.result;
            document.body.insertBefore(img,chooseImg);
            img.onload = function(){
                var canvas = document.createElement(&#39;canvas&#39;);
                canvas.width = img.clientWidth;
                canvas.height = img.clientHeight;
                var context = canvas.getContext(&#39;2d&#39;);
                context.drawImage(img,0,0,canvas.width,canvas.height);
                var rate = document.getElementById("rate").value || 100;
                var imgUrl = canvas.toDataURL(file.type,rate/100);
                result.innerHTML = &#39;压缩后:<img src="&#39;+ imgUrl +&#39;" />&#39;;
                result.style.display = &#39;block&#39;;
                img.style.display = &#39;none&#39;;
            };
        };
    }
    else{
        result.innerHTML = &#39;<span style="color: red;">文件类型有误!</span>&#39;;
    }
};
Copy after login

The test found that the JPEG format image compression effect through Canvas is the best, while the PNG compression effect is not obvious, and sometimes it becomes larger.

The above content is the sample code of Canvas and image compression. I hope it can help everyone.

Related recommendations:

How to use canvas to realize the interaction between the ball and the mouse

How to use canvas to create the effect of particle fountain animation

Commonly used drawing techniques in Canvas in HTML5

Canvas makes mouse dragging to draw graphics

Detailed example of html5 using canvas to implement image download function

The above is the detailed content of Sample code for Canvas and image compression. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!