How to color an image based on a dynamically changing percentage value?

霸气de小男生 提交于 2019-12-11 10:36:43

问题


I have an image which i want to fill with some color based on a dynamically changing value that represents percentage, e.g. if the value is 50% half of the image should be colored.

How to achieve that using JavaScript (jQuery can be used)?


回答1:


You can accomplish that by utilizing the clip CSS property, and a little bit of added markup to serve an underlaying container for the unrevealing background color.

Abstract

Place an element underneath the image for the faux color fill, and set its dimensions and position to match the images'. Then use JavaScript to clip the image dynamically - thus revealing the underlying color - by altering the clip value of the image element according to your needs (you can, of course, control each offset separately, e.g. left, bottom).

Note: To achieve specifically what you desire you can alter the underlying element to contain another image that suits your needs (i.e. a top image of an empty barrel, and a bottom image of a full one).

Implementation

In this example a slider is used to trigger the value change.

Markup

<input type="range"  min="0" max="100" id="slider" value="100" />
<div id="underlay"></div>
<img src="http://placekitten.com/500/207" id="image" />

Styles

#slider,
#image,
#underlay {
    /* absolute positioning is mandatory for clipped elements (#image) */
    position: absolute;
    left: 50px;
    width: 500px;
}
#image,
#underlay {
    top: 100px;
    height: 207px;
}
#image {
    /* initial clip state */
    clip: rect(auto, auto, auto, 500px);
}
#slider {
    top: 50px;
}
#underlay {
    background-color: #4C76A5;
}

Functionality

var img = document.getElementById('image');
var sld = document.getElementById('slider');

sld.addEventListener('change', function(e) {

    // get the slider value
    var val = e.srcElement.value;
    // calc the percentage to pass an absolute length value to the clip property
    var perc = img.width / 100 * val;

    // set the images' left offset clip accordingly
    img.style.clip = 'rect(auto, auto, auto, ' + perc + 'px)';
});

Live Demo

  • On jsFiddle

References

  • clip on Mozilla Developer Network
  • Browser support


来源:https://stackoverflow.com/questions/11692962/how-to-color-an-image-based-on-a-dynamically-changing-percentage-value

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