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



    <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> 

  • 相关阅读:
    输入/输出的格式和方法
    程序编译运行和exe运行之文件位置的区别
    ZOJ_3950_How Many Nines 解题报告及如何对程序进行测试修改
    [Offer收割]编程练习赛13 解题报告
    查找语言自带函数
    codeblocks下的汇编语言
    hiho一下 第144周(机会渺茫)解题报告及拓展
    关闭调试窗口快捷方式
    编写程序一个位置的快速到达和修改
    poj3660(Cow Contest)解题报告
  • 原文地址:https://www.cnblogs.com/access520/p/5711036.html
Copyright © 2020-2023  润新知