在HTML5画布上渲染之前更改图像像素的最快方法

时间:2014-10-05 14:05:21

标签: javascript html5 canvas

我有一个(大)HTML5画布。它使用context.drawImage()从文件渲染图片,这非常快。 (请注意,同一画布上有多张图片。)

现在我需要对画布上的像素执行一些操作,基本上我需要执行Alpha混合,这会使图片的某些区域变暗。所以我使用了这种方法。

 //create an invisible canvas so that we don't do the actual rendering of the image
 var invisibleCanvas = document.createElement('canvas');
 invisibleCanvas.width = myWidth;
 invisibleCanvas.height = myHeight;

 var invContext = invisibleCanvas.getContext('2d');
 invContext.drawImage(imageObj, 0, 0, invisibleCanvas.width, invisibleCanvas.height);
 var imageData = invContext.getImageData(0, 0, invisibleCanvas.width, invisibleCanvas.height)
 var pixelComponents = imageData.data;

 var dkBlendingAmount = 0.5;
 for (var i = 0; i < pixelComponents.length; i += 4)
 {
    //there are a few extra checks here to see if we should do the blending or not

    pixelComponents[i] = pixelComponents[i] * dkBlendingAmount;
    pixelComponents[i+1] = pixelComponents[i+1] * dkBlendingAmount;
    pixelComponents[i+2] = pixelComponents[i+2] * dkBlendingAmount;
 }

 //this is the real place where I want it
 context.putImageData(imageData, xOffset, yOffset);

有没有办法让它更快?有没有办法直接从我的imageObj获取图像数据,而不必将其放在画布上,获取数据,转换它并将其放在另一个画布上?

0 个答案:

没有答案