user7892745
user7892745

Reputation:

Javascript Canvas Context Filter Only Applies To Blur

I am interested in making CSS filter's apply to a javascript canvas's image data. I have already found the canvas context filter. For example, this works with blur.

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>

While the code below doesn't work because if it did, then the whole screen would be white.

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

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

Also, as a side note, I do not care to have my application available on non Chrome/FF browsers, so please don't mention this unless if you have a polyfill for it.

Upvotes: 1

Views: 2567

Answers (2)

user7892745
user7892745

Reputation:

I have found the answer to my question: you have to draw the canvas onto itself to apply the filters.

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);
Before<br />
<canvas id=1></canvas><br />
After<br />
<canvas id=2></canvas>

Upvotes: 2

Oleg Yakovchuk
Oleg Yakovchuk

Reputation: 1

You don't see the brightness effect because text has black color for default.

Brightness changes the concentration of selected color and mixes it with black color, so, for example, if you have red-colored text and brightness property 70%, then your text will have 70% red and 30% black color.

Just add color in strokeStyle:

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

ctx.filter = 'brightness(70%)';
ctx.font = '48px serif';
ctx.strokeStyle = 'red';
ctx.strokeText('Hello world', 50, 100);
<canvas id="canvas"></canvas>

Upvotes: 0

Related Questions