• 企业400电话
  • 微网小程序
  • AI电话机器人
  • 电商代运营
  • 全 部 栏 目

    企业400电话 网络优化推广 AI电话机器人 呼叫中心 网站建设 商标✡知产 微网小程序 电商运营 彩铃•短信 增值拓展业务
    将HTML5 Canvas的内容保存为图片借助toDataURL实现
    主要思想是借助Canvas自己的API - toDataURL()来实现,整个实现
    HTML + JavaScript的代码很简单。

    复制代码
    代码如下:

    <html>
    <meta http-equiv="X-UA-Compatible" content="chrome=1">
    <head>
    <script>
    window.onload = function() {
    draw();
    var saveButton = document.getElementById("saveImageBtn");
    bindButtonEvent(saveButton, "click", saveImageInfo);
    var dlButton = document.getElementById("downloadImageBtn");
    bindButtonEvent(dlButton, "click", saveAsLocalImage);
    };
    function draw(){
    var canvas = document.getElementById("thecanvas");
    var ctx = canvas.getContext("2d");
    ctx.fillStyle = "rgba(125, 46, 138, 0.5)";
    ctx.fillRect(25,25,100,100);
    ctx.fillStyle = "rgba( 0, 146, 38, 0.5)";
    ctx.fillRect(58, 74, 125, 100);
    ctx.fillStyle = "rgba( 0, 0, 0, 1)"; // black color
    ctx.fillText("Gloomyfish - Demo", 50, 50);
    }
    function bindButtonEvent(element, type, handler)
    {
    if(element.addEventListener) {
    element.addEventListener(type, handler, false);
    } else {
    element.attachEvent('on'+type, handler);
    }
    }
    function saveImageInfo ()
    {
    var mycanvas = document.getElementById("thecanvas");
    var image = mycanvas.toDataURL("image/png");
    var w=window.open('about:blank','image from canvas');
    w.document.write("<img src='"+image+"' alt='from canvas'/>");
    }
    function saveAsLocalImage () {
    var myCanvas = document.getElementById("thecanvas");
    // here is the most important part because if you dont replace you will get a DOM 18 exception.
    // var image = myCanvas.toDataURL("image/png").replace("image/png", "image/octet-stream;Content-Disposition: attachment;filename=foobar.png");
    var image = myCanvas.toDataURL("image/png").replace("image/png", "image/octet-stream");
    window.location.href=image; // it will save locally
    }
    </script>
    </head>
    <body bgcolor="#E6E6FA">
    <div>
    <canvas width=200 height=200 id="thecanvas"></canvas>
    <button id="saveImageBtn">Save Image</button>
    <button id="downloadImageBtn">Download Image</button>
    </div>
    </body>
    </html>

    运行效果如下
    上一篇:仿酷狗html5手机音乐播放器主要部分代码
    下一篇:HTML5拖拽文件到浏览器并实现文件上传下载功能代码
  • 相关文章
  • 

    © 2016-2020 巨人网络通讯 版权所有

    《增值电信业务经营许可证》 苏ICP备15040257号-8

    将HTML5 Canvas的内容保存为图片借助toDataURL实现 将,HTML5,Canvas,的,内容,保,