how to change the color of an image in a HTML5 Canvas without changing its pattern

Viewed 12844

I want to change the background color of this image while keeping the form, the effects and the contour of the image.

<canvas id="canvas01" width="1200" height="800"></canvas>
<script>
    function drawImage(imageObj,x, y, width, height){
        var canvas = document.getElementById('canvas01');
        var context = canvas.getContext('2d');
        context.drawImage(imageObj, x, y, width, height);
    }
    var image = new Image();
    image.onload = function(){
        drawImage(this, 400, 100, 320, 450);
    };
    image.src ="images/658FFBC6.png";
</script>
3 Answers

You can combine filters on a single line of code before performing your draw operation, like this:

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const image = document.getElementById('source');

ctx.filter = 'hue-rotate(120deg) grayscale(10%) brightness(150%)';
ctx.drawImage(image, 10, 10, 180, 120);
<canvas id="canvas"></canvas>
<div style="display:none;">
  <img id="source"
       src="https://interactive-examples.mdn.mozilla.net/media/examples/gecko-320-213.jpg">
</div>

Related