html canvas toblob 和下载图片

Posted qianbo_insist

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了html canvas toblob 和下载图片相关的知识,希望对你有一定的参考价值。

toblob

canvas 的toblob函数是直接生成二进制而不是base64 ,节省了流浪,下载直接为png图片。如下图所示。

show me the code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Canvas toBlob and download</title>
</head>
<body>
<canvas id="canvas"></canvas>
</body>
<script>
	function downloadByBlob(blobObj) {
        const link = document.createElement('a');
        link.style.display = 'none';
        const downloadUrl = window.URL.createObjectURL(blobObj);
        link.href = downloadUrl;
        link.download = `test.png`;
        document.body.appendChild(link);
        link.click();
        link.remove();
    }
    var canvas = document.getElementById("canvas");
	    canvas.width = 640;
        canvas.height = 360;
        var context = canvas.getContext('2d');
		context.rect(0,0,640,360);  
        context.moveTo(10,10);
        context.lineTo(100,100);
        context.lineTo(500,100);
        context.lineWidth = 10;
        context.strokeStyle = "red";
        context.stroke();

 
    //第一个参数是回调函数
    canvas.toBlob(
        function (blob) {
            var newImg = document.createElement("img"),
                url = URL.createObjectURL(blob);
            downloadByBlob(blob);
            //加载后销毁
            newImg.onload = function () {
                // no longer need to read the blob so it's revoked
                URL.revokeObjectURL(url);
            };
 
            //img标签属性赋值
            newImg.src = url;
            //添加为子元素
            document.body.appendChild(newImg);
        });
</script>
</html>

以上是关于html canvas toblob 和下载图片的主要内容,如果未能解决你的问题,请参考以下文章

html canvas blob image 污染源

vue常用组件

Canvas保存图片到七牛云

Canvas保存图片到七牛云

javascript canvas全部API

使用 toBlob 下载画布图像