Javascript Canvas上下文过滤器仅适用于模糊

时间:2017-05-12 02:51:37

标签: javascript google-chrome image-processing html5-canvas css-filters

我有兴趣将CSS过滤器应用于javascript画布的图像数据。我已经找到了canvas context filter。例如,这适用于模糊。



var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');

ctx.filter = 'blur(3px)';
ctx.font = '48px serif';
ctx.strokeText('Hello world', 50, 100);

<canvas id="canvas"></canvas>
&#13;
&#13;
&#13;

虽然下面的代码不起作用,但如果确实如此,则整个屏幕都是白色的。

&#13;
&#13;
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');

ctx.filter = 'brightness(1000%)';
ctx.font = '48px serif';
ctx.strokeText('Hello world', 50, 100);
&#13;
<canvas id="canvas"></canvas>
&#13;
&#13;
&#13;

另外,作为附注,我不在乎我的应用程序在非Chrome / FF浏览器上可用,所以请不要提及此情况,除非你有一个polyfill用于它。

1 个答案:

答案 0 :(得分:1)

我找到了问题的答案:您必须将画布绘制到自身以应用滤镜。

&#13;
&#13;
var canvas1 = document.getElementById('canvas1');
var ctx1 = canvas1.getContext('2d');
var canvas2 = document.getElementById('canvas2');
var ctx2 = canvas2.getContext('2d');

ctx1.font = '48px serif';
ctx1.strokeStyle = 'red';
ctx1.strokeText('Hello world', 50, 50);
ctx1.filter = 'brightness(0%)';

ctx2.font = '48px serif';
ctx2.strokeStyle = 'red';
ctx2.strokeText('Hello world', 50, 50);
ctx2.filter = 'brightness(0%)';
ctx2.drawImage(canvas2, 0, 0);
&#13;
Before<br />
<canvas id=1></canvas><br />
After<br />
<canvas id=2></canvas>
&#13;
&#13;
&#13;