You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用JavaScript获取HTML canvas元素对应的源图片文件名

解决方案

通用方案(全场景适配)

Canvas本身不会存储绘制所用的源图片地址,你可以通过拦截canvas绘制API的方式自动记录所有绘制到目标canvas的图片资源:

  1. 页面加载初期先注入hook代码,拦截drawImage方法:
const originalDraw = CanvasRenderingContext2D.prototype.drawImage;
const canvasSourceMap = new WeakMap();

CanvasRenderingContext2D.prototype.drawImage = function (...args) {
  if (args[0] instanceof Image) {
    canvasSourceMap.set(this.canvas, args[0].src);
  }
  originalDraw.apply(this, args);
}
  1. 获取目标canvas后直接提取文件名:
const canvas = document.getElementById('field-area');
const fullSrc = canvasSourceMap.get(canvas);
// 从完整资源路径中提取带参数的文件名
const targetFileName = fullSrc.split('/').pop();
// 输出结果:field_1920x1080.png?v=8
console.log(targetFileName);

特定站点快捷方案

针对你提到的站点,可直接读取全局预加载的资源配置获取地址,无需拦截API:

// 直接读取站点全局存储的场地背景资源地址
const fieldSrc = window.futbinConfig.squadBuilder.fieldBg;
const targetFileName = fieldSrc.split('/').pop();
console.log(targetFileName);

内容的提问来源于stack exchange,提问作者Aleksander Schultz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 16:30:00