使用canvas在图片中签名

需求:

  • 在图片中签上作者的名字,并在图片指定下划线位置居中显示。

  • 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');

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值