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

Tutorial on converting canvas to image example

巴扎黑
Release: 2017-05-27 10:12:36
Original
1826 people have browsed it

Sometimes, we want to store the drawn canvas as a local image. What should we do? Canvas provides an important method toDataURL(), which can convert the pattern in the canvas into base64 encoding format. png or other format pictures (according to the mine type parameters you passed in), and then return Data URL data. Next let's see how it is implemented.

A canvas canvas for the html page:

<canvas id="canvas"></canvas>
<button class="button-balanced" id="save">save</button>
<br />
<a href="" download="canvas_love.png" id="save_href">
    <img src="" id="save_img"/>
</a>
Copy after login

The corresponding js code implementation:

var c=document.getElementById("canvas");
function drawLove(canvas){
    let ctx = canvas.getContext("2d");
    ctx.beginPath();
    ctx.fillStyle="#E992B9";
    ctx.moveTo(75,40);
    ctx.bezierCurveTo(75,37,70,25,50,25);
    ctx.bezierCurveTo(20,25,20,62.5,20,62.5);
    ctx.bezierCurveTo(20,80,40,102,75,120);
    ctx.bezierCurveTo(110,102,130,80,130,62.5);
    ctx.bezierCurveTo(130,62.5,130,25,100,25);
    ctx.bezierCurveTo(85,25,75,37,75,40);
    ctx.fill();
}
drawLove(c); 

var butSave = document.getElementById("save");
butSave.onclick=function(){
    var svaeHref = document.getElementById("save_href");
    /*
     * 传入对应想要保存的图片格式的mime类型
     * 常见:image/png,image/gif,image/jpg,image/jpeg
     */
    var img = document.getElementById("save_img");
    var tempSrc = canvas.toDataURL("image/png");
    svaeHref.href=tempSrc; 
    img.src=tempSrc;  
};
Copy after login

After clicking the save button, the picture will be displayed. Click the picture to pop up the download dialog box.

The effect is as follows:

Tutorial on converting canvas to image example

The above is the detailed content of Tutorial on converting canvas to image example. 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!