0

我正在尝试从 ImageData 数组构建一个水平透明图像,它将用作动画的精灵图像。您能否解释一下,如何将帧传递给更宽的画布(宽度 X countFrames)以及如何在迭代中移动 ImageData 宽度的偏移量?谢谢你。

var spriteFrames = [];

for (var i = 0; i < data.animator.frames; i++) {
    var imageData = new ImageData( 500, 400 );
    spriteFrames.push( imageData.data );
}

function generateSprite( data, width, height, numFrames ) {
    var canvas = document.createElement('canvas'),
        ctx = canvas.getContext('2d');
    canvas.width = width * numFrames,
    canvas.height = height;
    var idata = ctx.getImageData(0, 0, width * numFrames, height);
    var buffer = new Uint8ClampedArray( width * numFrames * height * 4);

    // some logic here
    for (var a = 0; a < data.length; a++) {

        for( var i = 0; i < data[a].length; i+=4 ) {

            var pos = i * numFrames;

            buffer[pos]   = data[a][i];
            buffer[pos+1] = data[a][i+1];
            buffer[pos+2] = data[a][i+2];
            buffer[pos+3] = data[a][i+3];

        }
    }

    idata.data.set(buffer);
    ctx.putImageData(idata, 0, 0);

    return canvas.toDataURL();
}

img.src = generateSprite( spriteFrames, width, height, spriteFrames.length );
4

1 回答 1

0

如此轻松

for (var a = 0; a < spriteFrames.length; a++) {
    ctx.putImageData( spriteFrames[a].image, width * a, 0 );
}
于 2019-11-21T10:01:38.327 回答