Fabricjs 无法在“WebGLRenderingContext”上执行“texImage2D”:图像元素包含跨域数据,可能无法加载

man*_*the 1 fabricjs reactjs

我正在使用 Amazon S3 和云前端。图片网址看起来像https://t.pimg.jp/061/089/535/2/61089535.jpg

我的代码看起来像

const imgUrl = 'https://t.pimg.jp/061/089/535/2/61089535.jpg';
fabric.util.loadImage(imgUrl, function(imgObj) {
    const oImg = new fabric.Image(imgObj, {
        crossOrigin: 'anonymous',
    });

    ...
});
Run Code Online (Sandbox Code Playgroud)

图片加载成功。但是当我对该图像应用过滤器时,就会出现错误。

已经在 s3 存储桶中应用了 cors 配置

<CORSConfiguration>
 <CORSRule>
   <AllowedOrigin>*</AllowedOrigin>
   <AllowedMethod>GET</AllowedMethod>
   <AllowedHeader>*</AllowedHeader>
 </CORSRule>
</CORSConfiguration>
Run Code Online (Sandbox Code Playgroud)

有谁知道如何修复?

shk*_*per 5

  1. 如果要使用util.loadImage(),则应为其提供 crossOrigin参数。在您的代码中,您crossOrigin: 'anonymous'在回调中设置了 - 那时已经使用错误的 CORS 策略下载了图像。
  2. 您问题中的图像实际上没有 access-control-allow-origin设置标题,至少在我撰写本文时没有。所以我使用了不同的图像作为示例:

const canvas = new fabric.Canvas('c')
const imgUrl = 'https://c1.staticflickr.com/9/8873/18598400202_3af67ef38f_q.jpg'

fabric.util.loadImage(imgUrl, (imgObj) => {
    const img = new fabric.Image(imgObj)
    img.filters.push(new fabric.Image.filters.Grayscale())
    img.applyFilters()
    canvas.add(img)
}, null, 'anonymous')
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.6.2/fabric.js"></script>
<canvas id="c" width="300" height="200"></canvas>
Run Code Online (Sandbox Code Playgroud)

我还建议使用fabric.Image.fromURL()- 这是加载图像的一种更清晰的方式:

fabric.Image.fromURL(imgUrl, (img) => {
    img.filters.push(new fabric.Image.filters.Grayscale())
    img.applyFilters()
    canvas.add(img)
}, {crossOrigin: 'anonymous'})
Run Code Online (Sandbox Code Playgroud)