javascript - 在 javascript 中手动创建图像并根据 Alpha channel 进行绘制?

标签 javascript html canvas

我目前正在尝试创建一个页面,其中包含动态生成的图像(不是形状),绘制到 Canvas 中以创建动画。

我尝试的第一件事如下:

//create plenty of those:
var imageArray = ctx.createImageData(0,0,16,8);
//fill them with RGBA values...
//then draw them
ctx.putImageData(imageArray,x,y);

问题在于图像重叠,并且 putImageData 只是...将数据放入上下文中,而不考虑 w3c 中指定的 Alpha channel :

pixels in the canvas are replaced wholesale, with no composition, alpha blending, no shadows, etc.

所以我想,我怎样才能使用 Image 而不是 ImageData 呢?

我试图找到一种方法来实际将 ImageData 对象放回到图像中,但它似乎只能放在 Canvas 上下文中。因此,作为最后的手段,我尝试使用 16x8 Canvas (图像的大小)的 toDataURL() 方法,并将结果粘贴为我的 src ~600 张图像。

结果很漂亮,但是占用了我 100% 的 CPU...(使用 putImageData 时却没有,约 5% cpu)我的猜测是,由于某种未知的原因,图像每次绘制时都会从 image/png 数据 URI 重新加载...但这很奇怪...不是吗?它似乎也比我以前的技术需要更多的 RAM。

因此,我不知道如何实现我的目标。

如何在 JavaScript 中动态创建 alpha channel 图像,然后以可观的速度在 Canvas 上绘制它们?

使用 Java 小程序是唯一真正的替代方案吗?

感谢您的宝贵时间。

最佳答案

不知道你真正想要完成什么:

您看过渲染上下文的 drawImage 方法吗? 基本上,它会为您进行组合(由 globalCompositeOperation 属性指定)——并且它允许您传入一个 canvas 元素作为源。

所以可能可以做一些类似的事情:

var offScreenContext = document.getCSSCanvasContext( "2d", "synthImage", width, height);
var pixelBuffer = offScreenContext.createImageData( tileWidth, tileHeight );
// do your image synthesis and put the updated buffer back into the context:
offScreenContext.putImageData( pixelBuffer, 0, 0, tileOriginX, tileOriginY, tileWidth, tileHeight );
// assuming 'ctx' is the context of the canvas that actually gets drawn on screen
ctx.drawImage(
  offScreenContext.canvas,                          // => the synthesized image
  tileOriginX, tileOriginY, tileWidth, tileHeight,  // => frame of offScreenContext that get's drawn
  originX, originY, tileWidth, tileHeight           // => frame of ctx to draw in
);

假设您有一个想要循环播放的动画,这还有一个额外的好处,即只需将帧生成一次到某种 Sprite 映射中,以便在后续迭代中您只需要调用 ctx.drawImage() - 当然,以增加内存占用为代价...

关于javascript - 在 javascript 中手动创建图像并根据 Alpha channel 进行绘制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4117992/

相关文章:

html - css first-of-type 在其他类下

javascript - 使 Canvas 无限

javascript - 覆盖原型(prototype)方法

javascript - 使用 jQuery 验证输入的最佳方法是什么? onChange/onKeyUp。还是其他什么?

html - jQuery 手机 : Dynamically loaded content bloating the DOM

html - li 元素的完全对齐

javascript - 如何停止我的尾随线导致对象因数组大小而减慢

javascript - html5 Canvas 和 javascript 的奇怪行为

javascript - 使用 React 和 Gatsby 将 Prop 从 parent 传递给 child

javascript - 在 AngularJS 中使用元素属性评估作用域对象