canvas图片保存

sunny红
sunny红 发布于 7 天前 浏览:123 类型:原创 - 教程 分类:HTML/CSS - Canvas 二维码: 作者原创 版权保护
<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");
            succimg.src=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" onClick="saveAsLocalImage()">Download Image</button>
    <img src="" id="succimg" />
</div>
</body>
</html>
标签:
z
给个赞 0 人点赞
收藏 0 人收藏
评论 已有 0 条评论;以下用户言论只代表其个人观点,不代表 前端网(QDFuns) 的观点或立场。
登录 以后才能发表评论
最新评论
还没有任何评论呢,赶紧抢先来一发吧!
sunny红 sunny红 作者

作者最新