JS: Alter Color for specific image in HTML Canvas

江枫思渺然 提交于 2021-01-28 07:31:55

问题


Let say I got the sprite to the left and I want to apply a red filter over the image before drawing it in a canvas so it looks like the sprite to the right. http://puu.sh/6dQ0E.png

Is there a way to do that? It could be done in two steps, but I don't know if it's possible to draw the geometric figure that has the exact same shape than the image. (Ex: Drawing a rectangle over it won't match.)

Note: I want the filter to only be applied to this image, not the whole canvas.


回答1:


You can combine 2 filtering operations to draw the red filter only on top of your existing sprite.

globalCompositeOperation="source-atop" will cause new drawings to only draw on top of existing non-transparent pixels.

globalAlpha will make your new drawings semi-transparent.

Taken together, you can draw a semi-transparent filter that only fills where your non-transparent ghost exsits.

Then just draw a red rectangle over your existing sprite (the rectangle will only be visible inside the existing ghost).

enter image description here

ctx.drawImage(ghostSprites,0,0);
ctx.globalAlpha=0.62;
ctx.globalCompositeOperation="source-atop";
ctx.fillStyle="red";
ctx.fillRect(spriteX,spriteY,spriteWidth,spriteHeight);

Demo: http://jsfiddle.net/m1erickson/W4XrG/

From here...

Notice the black outlines of your sprite become washed from the red filter.

You could also use context.getImageData to grab only the black pixels of your ghost. Then redraw those black pixels over your red-filtered ghost so the black outlines are not washed. If you feel ambitious, you could give that a try!

Good luck with your project!

Here’s code

<style>
    body{ background-color: ivory; padding:20px;}
    #canvas{border:1px solid red;}
</style>

<script>
$(function(){

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

    var img=new Image();
    img.onload=start;
    img.crossOrigin="anonymous";
    img.src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/temp0a.png";
    function start(){}

    var spriteX=0;
    var spriteY=0;
    var spriteWidth=133;
    var spriteHeight=161

    $("#recolor").click(function(){
        ctx.drawImage(img,0,0);
        ctx.globalAlpha=0.62;
        ctx.globalCompositeOperation="source-atop";
        ctx.fillStyle="red";
        ctx.fillRect(spriteX,spriteY,spriteWidth,spriteHeight);
    });

}); // end $(function(){});
</script>

</head>

<body>
    <p>Before</p>
    <img src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/temp0a.png">
    <p>After</p>
    <button id="recolor">Click to recolor the green sprite</button><br>
    <canvas id="canvas" width=300 height=161></canvas>
</body>
</html>


来源:https://stackoverflow.com/questions/20999759/js-alter-color-for-specific-image-in-html-canvas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!