ngx-capture无法捕获截图区域内的<img>元素问题求助
解决ngx-capture无法捕获
元素的问题
问题说明
使用ngx-capture对包含图片的指定区域截图时,元素无法被捕获,截图结果中图片位置显示空白。
原代码示例
HTML代码
<div #screen style="background: red; color: #FFFFFF"> <img width="100" height="100" alt="image" src="https://images.unsplash.com/photo-1546961329-78bef0414d7c?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=387&q=80" /> <hello name="{{ name }}"></hello> <p>Start editing to see some magic happen :)</p> </div> <button (click)="onCapture()">Capture</button> <img src="{{ img }}" />
Component.ts代码
import { Component, ViewChild } from "@angular/core"; import { NgxCaptureService } from "ngx-capture"; import { tap } from "rxjs/operators"; @Component({ selector: "my-app", templateUrl: "./app.component.html", styleUrls: ["./app.component.css"] }) export class AppComponent { public name = "Angular"; public img = ""; @ViewChild("screen", { static: true }) screen: any; constructor(private captureService: NgxCaptureService) {} onCapture() { this.captureService .getImage(this.screen.nativeElement, true) .pipe( tap(img => { this.img = img; console.log(img); }) ) .subscribe(); } }
原因分析
ngx-capture底层依赖html2canvas实现截图功能,而浏览器的同源策略会阻止跨域资源被canvas读取,导致外部域名的图片无法被捕获并渲染到截图中。
解决方案
方法1:添加跨域属性(推荐,需图片服务器支持)
给<img>元素添加crossorigin="anonymous"属性,同时确保图片服务器配置了允许匿名跨域访问的CORS响应头:
<img width="100" height="100" alt="image" crossorigin="anonymous" src="https://images.unsplash.com/photo-1546961329-78bef0414d7c?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=387&q=80" />
方法2:将图片转为Base64后渲染
如果无法修改图片服务器的CORS配置,可以先将图片转为Base64格式,再渲染到页面上绕开跨域限制:
// 在Component中添加图片转Base64的方法 async loadImageAsBase64(url: string): Promise<string> { const response = await fetch(url); const blob = await response.blob(); return new Promise((resolve, reject) => { const reader = new FileReader(); reader.onloadend = () => resolve(reader.result as string); reader.onerror = reject; reader.readAsDataURL(blob); }); } // 组件初始化时加载图片 imgSrc: string = ''; async ngOnInit() { const imgUrl = "https://images.unsplash.com/photo-1546961329-78bef0414d7c?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=387&q=80"; this.imgSrc = await this.loadImageAsBase64(imgUrl); }
HTML中使用转换后的Base64地址:
<img [src]="imgSrc" width="100" height="100" alt="image" />
方法3:使用同域图片
将图片下载到本地项目的静态资源目录(如assets),使用相对路径引用,彻底避免跨域问题:
<img src="./assets/your-local-image.jpg" width="100" height="100" alt="image" />
验证修改
完成上述任意一种修改后,点击Capture按钮,截图结果中将正常显示图片内容。
内容的提问来源于stack exchange,提问作者Siddhesh Shedge
相关产品推荐
相关产品推荐

