使用Image和canvas实现下载证书功能

项目中需要实现点击按钮下载证书这个功能,大佬说用canvas实现。记录一下如何实现。

创建图片img标签

const img = new Image() //创建图片img标签

图片的属性

  • url:图片的地址
  • crossOrigin
    • 图片获取过程中是否开启CORS功能
    • 两个值 anonymoususe-credentials
    • anonymous:会在请求中的header中的带上Origin属性,但请求不会带上cookie和其他的一些认证信息;
    • use-credentials:会在请求中的header中的带上Origin属性并且带上cookie和其他的一些认证信息;
    • 在使用这两个值时都需要server端在response的header中带上Access-Control-Allow-Credentials属性。
  img.src = this.url; 
  img.crossOrigin = 'anonymous'; 

图片onload属性

  • onload 事件在图片加载完成后立即执行。
img.onload = function () {
	const canvas = document.createElement('canvas'); //创建canvas
}

以上,实现图片下载功能。

利用canvas给证书补充具体信息

  • width :宽度
  • height :高度
  • drawImage 将图片渲染到canvas里;
    • drawImage(image, x, y):image 是 image 或者 canvas 对象,x 和 y 是其在目标 canvas 里的起始坐标;
  • textAlign :文本对齐选项
  • textBaseline:文字垂直方向的对齐方式
  • font:字体样式
  • fillStyle:描述颜色和样式的属性
  • fillText:在 (x, y)位置填充文本的方法
    • 语法:ctx.fillText(text, x, y, [maxWidth])
    • x:文本起点的 x 轴坐标;
    • y:文本起点的 y 轴坐标:
    • text:使用当前的 font, textAlign, textBaselinedirection 值对文本进行渲染。
 img.onload = function () {
                const canvas = document.createElement('canvas'); //创建canvas
                console.log(img);
                const ctx = canvas.getContext('2d');
                const w_img = img.width;
                const h_img = img.height;
                console.log(h_img);
                let nu = 1;
                if (w_img > 1000) {
                    nu = w_img / 1000;
                }
                canvas.width = w_img / nu; // 设置宽度
                canvas.height = h_img / nu; // 设置高度
                ctx.drawImage(img, 0, 0, w_img / nu, h_img / nu); 
                // ctx.save();
                ctx.textAlign = textAlign;
                ctx.textBaseline = textBaseline;
                ctx.font = font;
                ctx.fillStyle = fillStyle;

                ctx.fillText(name, 175, h_img / nu - 360); // 名字位置
                ctx.fillText(dj, w_img / nu - 330, h_img / nu - 320); //等级位置
                ctx.fillText(bh, 300, h_img / nu - 105); //编号位置
                ctx.fillText(date, w_img / nu - 350, h_img / nu - 180); //日期位置
                const base64Url = canvas.toDataURL();
                // 使用a标签下载图片
                const $a = $("<a></a>").attr("href", base64Url).attr("download", '证书');
                $a[0].click();
            }

以上,就可以实现下载证书功能。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值