有两个最佳竞争者:
创建1×1图像数据,设置颜色,并
putImageData
在以下位置:var id = myContext.createImageData(1,1); // only do this once per page
var d = id.data; // only do this once per page
d[0] = r;
d[1] = g;
d[2] = b;
d[3] = a;
myContext.putImageData( id, x, y );使用
fillRect()
绘制像素(应该没有走样的问题):ctx.fillStyle = "rgba("+r+","+g+","+b+","+(a/255)+")";ctx.fillRect( x, y, 1, 1 );
我建议针对您关心的浏览器进行测试以实现最大速度。 截至2017年7月,
fillRect()在Firefox v54和Chrome
v59(Win7x64)上速度提高了5-6倍。
其他更明智的选择是:
使用
getImageData()/putImageData()
整个画布上; 这比其他选项要慢100倍。使用数据网址创建自定义图片并
drawImage()
用于显示它:var img = new Image;
img.src = “data:image/png;base64,” + myPNGEnprer(r,g,b,a);
// Writing the PNGEnprer is left as an exercise for the reader创建另一个img或画布,其中填充了您想要的所有像素,并用于
drawImage()
仅涂抹您想要的像素。这可能非常快,但是有一个局限性,就是您需要预先计算所需的像素。
请注意,我的测试并不尝试保存和恢复canvas上下文fillStyle
;这会降低fillRect()
性能。另请注意,我不是从一开始就做任何准备,也不是每次测试都测试完全相同的像素集。



