var canvas = document.querySelector('canvas');
var ctx = canvas.getContext('2d');
var init = function() {
var grd = ctx.createLinearGradient(0, 0, 150, 0);
grd.addColorStop(0, "blue");
grd.addColorStop(1, "red");
ctx.fillStyle = grd;
ctx.fillRect(0, 0, 150, 150100);
var grd2 = ctx.createLinearGradient(0, 0, 0, 150);
grd2.addColorStop(0, "green");
grd2.addColorStop(1, "yellow");
ctx.fillStyle = grd2;
ctx.fillRect(40, 0, 70, 150100);
}
var invert = function(p) {
//we get the data of the image
var imgData = canvas.getContext('2d').getImageData(0, 0, 150, 150100);
var pix = imgData.data;
// Loop over each pixel and apply the function
for (var i = 0, n = pix.length; i < n; i += 4) {
pix[i + 0] = Math.round((1 / (2 * p - 1)) * (255 - (255 * (1 - p) + pix[i + 0])));
pix[i + 1] = Math.round((1 / (2 * p - 1)) * (255 - (255 * (1 - p) + pix[i + 1])))
pix[i + 2] = Math.round((1 / (2 * p - 1)) * (255 - (255 * (1 - p) + pix[i + 2])))
// i+3 is alpha (the fourth element)
}
//Draw the image again
imgData.data = pix;
canvas.getContext('2d').putImageData(imgData, 0, 0);
}
init();
$('input').change(function() {
var v = $(this).val();
$('.filter').css('filter', 'invert(' + v + ')');
init();
invert(v);
})
bodyp {
margin: 0;
}
div,
canvas {
display: inline-block;
}
.grad {
height: 150px;100px;
width: 150px;
background: linear-gradient(to bottom, green, yellow)40px 0/70px 100% no-repeat, linear-gradient(to right, blue, red);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="grad"></div>
<div class="filter">
<div class="grad"></div>
<canvas><<canvas height="100" width="150"></canvas>
</div>
<p>Adjust the value of the invert filter</p>
<input type="range" value="0" min=0 max=1 step=0.05>