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中展示出来
}