HTML5 Canvas Brighten Image Filter Tutorial

To apply filter to an Konva.Image, we have to cache it first with cache()
function. Then apply filter with filters() function.

To brighten or darken an image with Konva, we can use the Konva.Filters.Brighten
filter and set the brightness amount with the brightness property.
The brightness property can be set to any integer between -1 and 1.
Negative values darken the image, and positive values brighten the image.

Instructions: Slide the control to adjust the brightness

For all available filters go to Filters Documentation.

Konva Brighten Image Demoview raw
<!DOCTYPE html>
<html>
<head>
<script src="https://unpkg.com/[email protected]/konva.min.js"></script>
<meta charset="utf-8" />
<title>Konva Brighten Image Demo</title>
<style>
body {
margin: 0;
padding: 0;
overflow: hidden;
background-color: #f0f0f0;
}

#slider {
position: absolute;
top: 20px;
left: 20px;
}
</style>
</head>

<body>
<div id="container"></div>
<input id="slider" type="range" min="-1" max="1" step="0.05" value="0" />
<script>
function loadImages(sources, callback) {
var images = {};
var loadedImages = 0;
var numImages = 0;
for (var src in sources) {
numImages++;
}
for (var src in sources) {
images[src] = new Image();
images[src].onload = function () {
if (++loadedImages >= numImages) {
callback(images);
}
};
images[src].src = sources[src];
}
}
function buildStage(images) {
var stage = new Konva.Stage({
container: 'container',
width: window.innerWidth,
height: window.innerHeight,
});

var layer = new Konva.Layer();

var lion = new Konva.Image({
image: images.lion,
x: 80,
y: 30,
draggable: true,
});

lion.cache();
lion.filters([Konva.Filters.Brighten]);
layer.add(lion);
stage.add(layer);
var slider = document.getElementById('slider');
slider.oninput = function () {
lion.brightness(slider.value);
};
}

var sources = {
lion: '/assets/lion.png',
};

loadImages(sources, buildStage);
</script>
</body>
</html>
Enjoying Konva? Please consider to support the project.