在一个画布上绘制多个图像

use*_*455 7 javascript html5 image

我有一个数组,其中包含有关image应如何绘制的所有信息.我想绘制2 images,当我这样做时,它只绘制最后一张图像.我能做什么?

for(i = 0; i < tiles.length; i++)
{
    var sourceX = tiles[i][5];
    var sourceY = tiles[i][6];
    var sourceWidth = tiles[i][9];
    var sourceHeight = tiles[i][10];
    var destWidth = sourceWidth;
    var destHeight = sourceHeight;
    var destX = tiles[i][7];
    var destY = tiles[i][8];

    var imageObj = new Image();
    imageObj.onload = function()
    {
        context.drawImage(imageObj, sourceX, sourceY, sourceWidth, sourceHeight, destX, destY, destWidth, destHeight);
    };
    imageObj.src = tiles[i][4];
}
Run Code Online (Sandbox Code Playgroud)

Rya*_*ang 11

我无法解释更具体的原因,但这是我想出的解决方案.这个对我有用.

const getContext = () => document.getElementById('my-canvas').getContext('2d');

// It's better to use async image loading.
const loadImage = url => {
  return new Promise((resolve, reject) => {
    const img = new Image();
    img.onload = () => resolve(img);
    img.onerror = () => reject(new Error(`load ${url} fail`));
    img.src = url;
  });
};

// Here, I created a function to draw image.
const depict = options => {
  const ctx = getContext();
  // And this is the key to this solution
  // Always remember to make a copy of original object, then it just works :)
  const myOptions = Object.assign({}, options);
  return loadImage(myOptions.uri).then(img => {
    ctx.drawImage(img, myOptions.x, myOptions.y, myOptions.sw, myOptions.sh);
  });
};

const imgs = [
  { uri: 'http://placehold.it/50x50/f00/000?text=R', x: 15, y:  15, sw: 50, sh: 50 },
  { uri: 'http://placehold.it/50x50/ff0/000?text=Y', x: 15, y:  80, sw: 50, sh: 50 },
  { uri: 'http://placehold.it/50x50/0f0/000?text=G', x: 15, y: 145, sw: 50, sh: 50 }
];

imgs.forEach(depict);
Run Code Online (Sandbox Code Playgroud)
#my-canvas { background: #7F7F7F; }
Run Code Online (Sandbox Code Playgroud)
<canvas id="my-canvas" width="80" height="210"></canvas>
Run Code Online (Sandbox Code Playgroud)


Jef*_*ney 5

我并不肯定,但 imageObj 可能不是您在 imageObj.onload 函数中期望的 imageObj。而不是做

 context.drawImage(imageObj, sourceX, sourceY,
Run Code Online (Sandbox Code Playgroud)

看看当你这样做时会发生什么

 context.drawImage(this, sourceX, sourceY,
Run Code Online (Sandbox Code Playgroud)