• Canvas保存图片保存到本地


    使用Canvas绘图,将图片保存到本地方法

    一、使用HTML5 a标签的download属性,将图片保存到本地,不需要链接服务器

    关于download属性:HTML5 <a>标签download 属性

    特别说明:这种方式只支持Google和FF,IE浏览器还不支持。(注:目前测试手机版浏览器也不支持)

        <canvas id="canvas1"></canvas>
        <br /><br />
        <input type="button" value="保存png图片" id="btn1" />
        <input type="button" value="保存jpg图片" id="btn2" />

    JS代码:

    //绘制图片
    var canvas = document.getElementById('canvas1');
    var ctx = canvas.getContext('2d');
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    ctx.fillStyle = "red";
    ctx.font = 'italic bold 30px Helvetica ';
    ctx.fillText('楷体', 50, 50);
    //绑定下载事件
    var btn = document.getElementById('btn1');
    btn.onclick = function () {
        var type = 'png';
        download(type);
    }
    document.getElementById('btn2').onclick = function () {
        var type = 'jpg';
        download(type);
    }
    //图片下载操作,指定图片类型
    function download(type) {
        //设置保存图片的类型
        var imgdata = canvas.toDataURL(type);
        //将mime-type改为image/octet-stream,强制让浏览器下载
        var fixtype = function (type) {
            type = type.toLocaleLowerCase().replace(/jpg/i, 'jpeg');
            var r = type.match(/png|jpeg|bmp|gif/)[0];
            return 'image/' + r;
        }
        imgdata = imgdata.replace(fixtype(type), 'image/octet-stream')
        //将图片保存到本地
        var saveFile = function (data, filename) {
            var link = document.createElement('a');
            link.href = data;
            link.download = filename;
            var event = document.createEvent('MouseEvents');
            event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
            link.dispatchEvent(event);
        }
        var filename = new Date().toLocaleDateString() + '.' + type;
        saveFile(imgdata, filename);
    }

     

    二、将生成图片数据返回服务器,通过http协议通知浏览器下载

    这种方式需要服务器处理,暂时没提供代码示例。

  • 相关阅读:
    python学习笔记4核心类型字典
    python学习笔记5核心类型元组和文件及其他
    python学习笔记11异常总结
    python学习笔记14类总结
    python学习笔记17常用函数总结整理
    python学习笔记1核心类型数字
    python学习笔记3核心类型列表
    python学习笔记16各种模块和开放工具收集整理
    源码、反码、补码
    素数
  • 原文地址:https://www.cnblogs.com/tianma3798/p/6121894.html
Copyright © 2020-2023  润新知