How to tint local icon image with transparent background?

时间:2019-01-09 22:21:51

标签: javascript html css canvas

I have looked into multiple solutions, but I could not find one that is suitable for what I need.

I have this local image

enter image description here When I hover the image I need to change only the black background to my theme color. A hover image is not a good solution because the theme color changes and it's difficult to get from the designer an image each time.

I have tried drawing the local image from both local source and from hidden div. And after that reading bit by bit and changing only the black bits to my theme color.

<div style='display: block'>
    <img id='img' src='back-icon-64.png' width='32' height='32' />
</div>
<canvas id="canvas" width=32 height=32>

The JavaScript

function drawImage() {

        var hiddenImg = document.getElementById('img')
        var canvas = document.getElementById("canvas")
        var ctx = canvas.getContext("2d")

        var image = new Image(32, 32)
        image.src=hiddenImg.src
        image.onload = function () {
            ctx.drawImage(image,0,0)
            var data = ctx.getImageData(0,0,32,32)
        }
    }

    function recolor(ctx) {

        var imgData = ctx.getImageData(0, 0, 32, 32);
        var data = imgData.data;

        for (var i = 0; i < data.length; i += 4) {
            red = data[i + 0];
            green = data[i + 1];
            blue = data[i + 2];
            alpha = data[i + 3];
            //console.log("rgba" + red + green, blue, alpha)
            console.log("rgba")
        }
    }
    drawImage()

Although I tried to set headers I am getting this error in the console:

Uncaught DOMException: Failed to execute 'getImageData' on 'CanvasRenderingContext2D': The canvas has been tainted by cross-origin data.

An working fiddle will be really helpful.

Thank you!

1 个答案:

答案 0 :(得分:3)

You can consider mix-blend-mode (you won't have transparency as you will need a white backgroud under the image)

.icon {
  width:64px;
  height:64px;
  display:inline-block;
  background:url(https://i.stack.imgur.com/Vi3wa.png)center/cover,
  #fff;
  position:relative;
}

.icon:hover::before {
  content:"";
  position:absolute;
  top:0;
  left:0;
  right:0;
  bottom:0;
  background:var(--c,red);
  mix-blend-mode:lighten;
}
<div class="icon">
</div>
<div class="icon" style="--c:blue;">
</div>
<div class="icon" style="--c:green;">
</div>

Selects the lighter of the backdrop and source colors.

The backdrop is replaced with the source where the source is lighter; otherwise, it is left unchanged.

https://drafts.fxtf.org/compositing-1/#valdef-blend-mode-lighten

相关问题