JSFiddle - React, Tailwind, and code Playground
HTML
<img src="http://publicdomainarchive.com/wp-content/uploads/2014/02/public-domain-images-free-high-resolution-quality-photos-unsplash-0079.jpg" title="Photo from publicdomainarchive.com" id="image" crossOrigin="anonymous"/>
<!-- For another test :
<img src="http://publicdomainarchive.com/wp-content/uploads/2014/12/public-domain-images-free-stock-photos-high-quality-resolution-downloads-public-domain-archive-18-1000x750.jpg" title="Photo from publicdomainarchive.com" id="image" crossOrigin="anonymous"/> -->
<h1 id="h1">My amazing title</h1>
CSS
img, h1 {
margin : 0;
padding : 0;
}
img {
width : 500px;
position : absolute;
top : 0;
left : 0;
z-index : 1;
}
h1 {
font-family : 'Open Sans', Arial;
font-size : 2em;
position : absolute;
top : 20px;
left : 0;
color : white;
z-index : 2;
padding : 3px 5px 3px 25px; /* attention this causes a margin of error !! */
}
JavaScript
var average_color_background = function(image, title) {
var treat_properties = function(elmt_propertie) {
return parseInt(elmt_propertie.replace(/px/, ''));
}
var image_width = treat_properties(getComputedStyle(image, null).width),
image_height = treat_properties(getComputedStyle(image, null).height),
title_width = treat_properties(getComputedStyle(title, null).width),
title_height = treat_properties(getComputedStyle(title, null).height),
title_top = treat_properties(getComputedStyle(title, null).top),
title_left = treat_properties(getComputedStyle(title, null).left);
var c = document.createElement('canvas');
c.width = image_width;
c.height = image_height;
c.style.position = "absolute";
c.style.top = 0;
c.style.left = 0;
c.style.zIndex = 0; // invisible calculation
document.getElementsByTagName('body')[0].appendChild(c);
var ctx = c.getContext("2d");
var image_bis = new Image();
image_bis.crossOrigin = 'anonymous'; // avoid security error
image_bis.onload = function(){
ctx.drawImage(image_bis,0,0,image_width,image_height);
var imageData = ctx.getImageData(title_left, title_top, title_width, title_height),
mapPixel = imageData.data;
var red = 0,
green = 0,
blue = 0,
length = 4 * title_width * title_height;
for(var i=0;i<length;i+=4) {
red += mapPixel[i];
green += mapPixel[i+1];
blue += mapPixel[i+2];
}
length = length / 4;
red = Math.round(red/length);
green = Math.round(green/length);
blue = Math.round(blue/length);
// display result, can easily be improved for something more beautiful (e.g. using complementary color) :
title.style.backgroundColor = 'rgb('+red+','+green+','+blue+')';
c.parentNode.removeChild(c);
...