【发布时间】:2019-12-11 12:53:02
【问题描述】:
我正在开发一个网站,可以在其中提供指向透明动画 gif(通常来自 giphy)的链接,并且我想在画布上呈现(动画)它,同时保持动画 gif 的透明度。这样可以改变 GIF 的动画速度。
我已经尝试使用以下方法
fastgif但三十帧中只有一帧显示图像,其余的完全透明。不透明的 Gif 也可以。gifuct-js但背景为黑色且不透明。我知道 gifuct 提供了一个透明度索引,但它在解码 gif 时没有显示。
我尝试了许多不同的 gif,包括不是来自使用 Photoshop 和 After Effects 创建的 giphy 但没有结果的 gif。
fastgif(其中all 是使用fetch 获取的解码后的gif)
import { Decoder } from 'fastgif'
const d = new Decoder()
window.fetch('https://media.giphy.com/media/tTutsU63rnHC8/giphy.gif')
.then((response) => response.arrayBuffer())
.then((buffer) => d.decode(buffer))
.then(async (frames) => {
const canvas = document.createElement('canvas');
canvas.width = all[0].imageData.width;
canvas.height = all[0].imageData.height;
const ctx = canvas.getContext('2d');
let frame = 0;
while (true) {
ctx.putImageData(all[frame].imageData, 0, 0);
await new Promise((resolve) => window.setTimeout(resolve, all[frame].delay));
if (++frame === all.length) {
frame = 0;
}
}
})
gifuct-js 这个我只尝试渲染一帧看透明度是否有效,但背景全黑,没有任何透明度。
var tempCanvas = document.createElement('canvas')
var tempContext = tempCanvas.getContext('2d')
window.fetch('https://media.giphy.com/media/tTutsU63rnHC8/giphy.gif')
.then((response) => response.arrayBuffer())
.then((buffer) => new GIF(buffer))
.then((gif) => gif.decompressFrames(true))
.then(async (frames) => {
const frame = frames[0]
const dims = frame.dims
c.width = dims.width
c.height = dims.height
tempCanvas.width = dims.width
tempCanvas.height = dims.height
const imageData = tempContext.createImageData(dims.width, dims.height)
tempContext.putImageData(imageData, 0, 0)
// set the patch data as an override
imageData.data.set(frame.patch)
let pix = imageData.data
ctx.clearRect(0, 0, c.width, c.height)
ctx.drawImage(tempCanvas, 0, 0)
ctx.putImageData(imageData, 0, 0)
image.src = tempCanvas.toDataURL('image/png')
})
如果将<img src='https://media.giphy.com/media/tTutsU63rnHC8/giphy.gif' /> 添加到网站,我希望渲染看起来像。带有透明背景的动画。
【问题讨论】:
标签: javascript html canvas gif transparent