1
I wanted to do this in the title of my box:
Is a linear-gradient
with the colors of the image and at the end the image.
I tried the codes below but it didn’t work here. What’s wrong?
script
<script>
function getAverageRGB(imgEl) {
var blockSize = 5, // only visit every 5 pixels
defaultRGB = {r:0,g:0,b:0}, // for non-supporting envs
canvas = document.createElement('canvas'),
context = canvas.getContext && canvas.getContext('2d'),
data, width, height,
i = -4,
length,
rgb = {r:0,g:0,b:0},
count = 0;
if (!context) {
return defaultRGB;
}
height = canvas.height = imgEl.naturalHeight || imgEl.offsetHeight || imgEl.height;
width = canvas.width = imgEl.naturalWidth || imgEl.offsetWidth || imgEl.width;
context.drawImage(imgEl, 0, 0);
try {
data = context.getImageData(0, 0, width, height);
} catch(e) {
/* security error, img on diff domain */
return defaultRGB;
}
length = data.data.length;
while ( (i += blockSize * 4) < length ) {
++count;
rgb.r += data.data[i];
rgb.g += data.data[i+1];
rgb.b += data.data[i+2];
}
// ~~ used to floor values
rgb.r = ~~(rgb.r/count);
rgb.g = ~~(rgb.g/count);
rgb.b = ~~(rgb.b/count);
return rgb;
}
function setTopImage() {
var rgb = getAverageRGB($("#articleImageSrc").get(0));
var string = "linear-gradient(to right, rgba(" + rgb.r + "," + rgb.g + "," + rgb.b + ", 1) 70%, rgba(0,0,0,0)), " + $("#articleImageSrc").parent().css("background-image") + " no-repeat center right";
var luma = 0.2126 * rgb.r + 0.7152 * rgb.g + 0.0722 * rgb.b; // per ITU-R BT.709
$("#articleImageSrc").parent().css("background", string);
if (luma < 150)
$("#articleImageSrc").parent().css("color", "#fff");
}
</script>
html
<div id="articleTopImage" class="card-body" style="background-image: url(https://4.bp.blogspot.com/-_FXd9ePuJkQ/WVVqF88kbmI/AAAAAAAA52M/b9aK-jyPb3Umxs1CR7GYp8w8dJ2m7zuCwCKgBGAs/s1600/Furnis%2BArticos.gif);">
<img src="https://4.bp.blogspot.com/-_FXd9ePuJkQ/WVVqF88kbmI/AAAAAAAA52M/b9aK-jyPb3Umxs1CR7GYp8w8dJ2m7zuCwCKgBGAs/s1600/Furnis%2BArticos.gif" style="display: none" id="articleImageSrc" crossorigin="" onload="setTopImage()">
RE: Aquecimento Caseiro </div>
css
#articleTopImage {
width: 100%;
padding: .75rem 1.25rem;
border-bottom: 1px solid rgba(0,0,0,.125);
border-top-left-radius: 4px;
border-top-right-radius: 4px;
font-size: 14px;
font-weight: bold;
}
Bootstrap.
Sometimes I give Ctrl + F5 in the browser ends up bugging and giving this error in the browser console "Uncaught Referenceerror: $ is not defined at setTopImage (14:129) at Htmlimageelement.onload (14:164)"
– Pedro
This is because the image is being loaded before jQuery.
– Sam
That’s right, it was worth <3
– Pedro