angular 11使用canvas实现文字图片合成一张图片

 html中显示

    
     <div [hidden]="!noshow">
      <img #img1 src="assets/img1.png" alt />
      <img #img2 src="assets/img2.png" alt />
      <img #img3 src="assets/img3.png" alt />
    </div>

    <canvas id="myCanvas" #myCanvas [hidden]="!noshow"></canvas>
    <div #photo class="photo"></div>

下面是在ts里的代码

 text: any =''
 text1: any =''
 text2: any =''
 text3: any =''


//需要在此处拿到html里的元素进行操作
 @ViewChild('img1', { static: false }) img1: any;
  @ViewChild('img2', { static: false }) img2: any;
  @ViewChild('img3', { static: false }) img3: any;
  @ViewChild('myCanvas', { static: false }) myCanvas: any;
  @ViewChild('photo', { static: false }) photo: any;






onCreateCanvas() {
    let img1 = this.img1.nativeElement //拿到图片,注意拿到图片内容需要添加nativeElement
    let img2 = this.img2.nativeElement
    let img3 = this.img3.nativeElement
    // console.log(img1.naturalWidth, img1.naturalHeight) 可获取图片的原始宽度和高度
    let img1Height = img1.naturalHeight
    let canvasWidth = 355 // 这里设置固定值
    let canvasHeight = 520 // 合成的画布高度为两张图片高度之和
    let canvas = this.myCanvas.nativeElement

    let context = canvas.getContext('2d')

    canvas.width = canvasWidth // canvas画布宽度
    canvas.height = canvasHeight // canvas画布高度
    context.fillStyle = '#ffffff';
    context.fillRect(0, 0, canvas.width, canvas.height);//给canvas设置背景白色
    // 将img1,img2,img2等依次加入画布

    context.drawImage(img1, 0, 0, 355, img1Height)  // 加入图片1
    context.drawImage(img2, 20, 400, 60, 60) // 加入图片2
    context.drawImage(img3, 260, 370, 80, 80) // 加入图片3


    context.fillStyle = 'black' // 设置文字的填充颜色
    context.font = '15px Georgia' // 设置文字的填充样式

    context.fillText(this.text, 100, 440) // 在画布中添加文字

    context.fillStyle = 'black' // 设置文字的填充颜色
    context.font = '15px Georgia' // 设置文字的填充样式
    context.fillText(this.text2, 245, 500) // 在画布中添加文字

    context.fillStyle = 'black' // 设置文字的填充颜色
    context.font = '18px Georgia' // 设置文字的填充样式
    context.fillText(this.text3, 20, 330) // 在画布中添加文字


    context.fillStyle = 'black' // 设置文字的填充颜色
    context.font = '12px Georgia' // 设置文字的填充样式
    context.fillText(this.text4, 20, 355) // 在画布中添加文字

    context.fillStyle = 'red' // 设置文字的填充颜色
    context.font = '25px Georgia' // 设置文字的填充样式
    context.fillText(this.text5, 85, 355) // 在画布中添加文字


    let newImg = new Image()
    newImg.src = canvas.toDataURL('image/png') // canvas画布导出图片

  this.photo.nativeElement.append(newImg) // 将图片插入div中展示出来

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值