const barW = 50; // display width of bar element on page. Note green-red bg image width must be 2 x barW
/*
This is where we apply the image to the bars. Because I create the image from a canvas, this is called as a callback from the image create process. If your image is just a plain web image and you know dimensions you could run this function in your document.ready() event.
*/
function makeBars(img) {
// apply the bar background to each tiny bar class (tbc)
$('.tbc').each(function() {
var num = parseFloat($(this).html(), 10) / 100; // I stored the % in the element html - read that.
var xPos = Math.round(-(barW * (1 - num))); // offset x by minus the bad proportion.
$(this).css({
backgroundImage: 'url(' + img.src + ')',
backgroundPositionX: xPos
}); // apply to element.
})
}
/*
Everything from here is optional - it generates an image via a canvas
*/
makeImg(makeBars); // call for the background image to be made
// this is all to generate an image - made from a canvas.
function makeImg(cbf) {
// add a stage
var s = new Konva.Stage({
container: 'container',
width: 800,
height: 200
});
// add a layer
var l = new Konva.Layer();
s.add(l);
// Add a good rect to the LAYER just to show the good amount.
var green = new Konva.Rect({
fill: 'blue',
width: 50,
height: 15,
x: 0,
y: 0,
opacity: 0.5
});
l.add(green);
// Add a bad rect to the LAYER just to show the good amount.
var red = new Konva.Rect({
fill: 'gold',
width: 50,
height: 15,
x: 50,
y: 0,
opacity: 0.5
});
l.add(red);
var bg;
var catchImg = function(img) {
cbf(img); // callback passing the new img
}
l.draw();
s.toImage({
callback: catchImg,
x: 0,
y: 0,
width: 100,
height: 15
})
$('#container').remove(); // now we have an image - trash the canvas.
}
.tbc {
display: inline-block;
width: 50px;
height: 15px;
line-height: 15px;
border: 1px solid #ccc;
text-align: center;
font-size: 8pt;
font-family: Calibri, sans-serif;
font-weight: bold;
color: blue;
}
.country {
display: inline-block;
width: 200px;
}
.info {
margin-top: 20;
font-size: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.rawgit.com/konvajs/konva/1.6.3/konva.min.js"></script>
<h1>Urban population rate by country </h1>
<div>
<div class='country'>China</div>
<div class='tbc'>57.6%</div>
</div>
<div>
<div class='country'>India</div>
<div class='tbc'>32%</div>
</div>
<div>
<div class='country'>U.S.</div>
<div class='tbc'>82.1%</div>
</div>
<div>
<div class='country'>Russia</div>
<div class='tbc'>73.2%</div>
</div>
<div>
<div class='country'>UK</div>
<div class='tbc'>81.2%</div>
</div>
<div>
<div class='country'>Burundi</div>
<div class='tbc'>11.5%</div>
</div>
<div class='info'><a href='http://www.worldometers.info/world-population/population-by-country/' target=''>Source: www.worldometers.info/</a>
<div id='container'>Temp: Used to contain canvas</div>