需求:
在图片中签上作者的名字,并在图片指定下划线位置居中显示。
canvas生成的图片可以下载并大小适合打印
实现思路:
用canvas实现一个画布
this.canvas = document.createElement('canvas');
this.canvas.className = 'cert-canvas';
this.ctx = this.canvas.getContext('2d');
然后将图片画在canvas上
let img = new Image();
img.src = img_path;
img.setAttribute('crossOrigin', 'anonymous');
img.onload = () => {
this.canvas.width = img.width; //画布的大小设为图片的大小
this.canvas.height = img.height;
this.ctx.drawImage(img, 0, 0, img.width, img.height);
};
在画布上添加文字
draw_time_text(text, x, y) {
this.ctx.font = '18px Helvetica';
this.ctx.textAlign = 'center';
this.ctx.fillText(text, x, y);
}
遇到的问题与解决方法:
让水平文字在画布指定位置居中显示
解决思路,找到指定位置下划线的中点, 然后使用this.ctx.textAlign = 'center';
,让文字以中点为中心居中显示
彩色文字
this.ctx.fillStyle = '颜色值';
非同源图片安全问题
Uncaught SecurityError: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.
canvas绘制图片,由于浏览器的安全考虑,如果在使用canvas绘图的过程中,使用到了外域的图片资源,那么在toDataURL()时会抛出安全异常。为了解决这个报错我们在引入图片的时候,将图片的CORS请求不设置凭据标志。即 img.setAttribute('crossOrigin', 'anonymous');