canvas导出为图片实例页面

代码:

CSS代码:
canvas { border: 1px solid #beceeb; background-color: #f0f3f9;}
                
HTML代码:
<canvas id="canvas"></canvas>
                
JS代码:
(function() {
    if (isNaN(window.screenX)) return;
    var canvas = document.querySelector("#canvas")
        , context = canvas.getContext("2d");
        
    // 添加文字
    context.save();
    context.font = "30px 微软雅黑";
    context.textAlign = "center";
    context.fillText("点击生成新图片", 150, 85);
    context.restore();
    
    // 点击事件
    canvas.addEventListener("click", function() {
        this.toBlob && this.toBlob(function(blob) {
            var newImg = document.createElement("img"),
                url = URL.createObjectURL(blob);
                
            newImg.onload = function() {
                // 移除
                URL.revokeObjectURL(url);
            };
            newImg.src = url;
            document.querySelector(".demo").appendChild(newImg);
        });    
    });
})();
                

效果: