Javascript createImageData() returns 0

Javascript createImageData() returns 0's

我尝试创建一个 canvas(这是图像的副本)以获得他的 RGBA 值的数组。 我究竟做错了什么? 帮助将不胜感激。

getColorArray(){
        var canvas = document.getElementById('myCanvas');
        var ctx = canvas.getContext('2d');
        var file = this.$el.querySelector("#image-preview-image");
        ctx.drawImage(file, 10, 10);
        
        const imageData = ctx.createImageData(10, 10);
        console.log(imageData);  
    }

createImageData() 只会创建一个新的色点数组,其中所有值为 0。您需要使用 getImageData() 来获取 canvas 上已有的数据。

const getColorArray = () => {
  var canvas = document.getElementById('myCanvas');
  var ctx = canvas.getContext('2d');
  var file = document.querySelector("#image-preview-image");
  ctx.drawImage(file, 0, 0);

  const imageData = ctx.getImageData(0, 0, 100, 100);
  console.log(imageData);
};

getColorArray();
<p>Image:
  <img id="image-preview-image" src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxMDAiIGhlaWdodD0iMTAwIj4KICA8Y2lyY2xlIGN4PSI1MCUiIGN5PSI1MCUiIHI9IjUwJSIgZmlsbD0iZ3JlZW4iIC8+Cjwvc3ZnPgo=" />
</p>
<p>Canvas:
  <canvas id="myCanvas" width="100" height="100"></canvas>
</p>