fillRect(0,0,0,1)和clearRect()有什么区别 [英] What is difference between fillRect(0,0,0,1) and clearRect()

查看:77
本文介绍了fillRect(0,0,0,1)和clearRect()有什么区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

两者之间是否有任何区别

  ctx.fillStyle ="rgba(0,0,0,1)";ctx.fillRect(0,0,100,100) 

  ctx.clearRect(0,0,100,100) 

性能或结果图像或画布数据有任何差异吗?

解决方案

(已更新为与有问题的OP更改相对应:) fillRect() ctx.fillStyle ="rgba(0,0,0,1)"; 将用不透明像素填充该区域,在这种情况下为黑色(注意alpha是标准化值[0,1]).

clearRect()进行相反的操作,所有像素"清除",以便位图变得透明(从技术上讲,该区域填充有黑色透明像素).

clearRect()已优化,而 fillRect()已绑定到合成/混合规则(Porter-Duff),因此前者更快.这意味着clearRect可以仅基于当前转换自由地直接填充区域,而fillRect 必须通过合成/混合公式,此外还要设置为(globalCompositeOperation).>

这当然是理论上的-取决于浏览器的实现.这是 简单性能测试 ,表明在Chrome填充中速度比清除速度要快(我不知道当今Chrome和canvas会发生什么情况),但是在Firefox中,清除速度比填充速度快很多倍,两者都比Chrome快得多:

在支持上下文的不透明度标志的浏览器中,可以禁用不需要的alpha,以使画布响应更快(此处的alpha与元素本身混合,并与浏览器背景混合).您将看到速度的提高,特别是Opera浏览器,但Firefox和Chrome也支持此标志.要禁用Alpha:

  var ctx = canvas.getContext("2d",{alpha:false}); 

Is there any difference between:

ctx.fillStyle = "rgba(0, 0, 0, 1)";
ctx.fillRect(0, 0, 100, 100)

and

ctx.clearRect(0, 0, 100, 100)

Any kind of difference in performance or resulting image or canvas data?

解决方案

(Updated to correspond to OPs changes in question:) fillRect() with ctx.fillStyle = "rgba(0, 0, 0, 1)"; will fill the region with opaque pixels, in this case black (note alpha is a normalized value [0,1]).

clearRect() does the opposite, "clearing" all pixels so that the bitmap becomes transparent (technically the region is filled with black transparent pixels).

clearRect() is optimized while fillRect() is bound to compositing/blending rules (Porter-Duff) so the former is faster. What this means is that clearRect is free to fill a region directly only based on current transformation, while fillRect has to go through the compositing/blending formula whatever that is set to (globalCompositeOperation) in addition.

That is of course in theory - it will depend on browser implementation. Here is a simple performance test showing that in Chrome filling is faster than clearing (I am not sure what goes on with Chrome and canvas nowadays), but in Firefox clearing is many times faster than filling, both significantly faster than Chrome:

In browsers which supports the opacity flag of the context, you can disable alpha if you don't need it, to make canvas respond even faster (the alpha here being blending with the element itself and composition with the browser background). You will see speed improvements in particular the Opera browser, but also Firefox and Chrome support this flag. To disable alpha:

var ctx = canvas.getContext("2d", {alpha: false});

这篇关于fillRect(0,0,0,1)和clearRect()有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆