Skip to content

Instantly share code, notes, and snippets.

@Bloodb0ne
Last active August 29, 2016 12:36
Show Gist options
  • Save Bloodb0ne/3232a7eed8af339c58b9 to your computer and use it in GitHub Desktop.
Save Bloodb0ne/3232a7eed8af339c58b9 to your computer and use it in GitHub Desktop.
Simple implementation of image placeholders using canvas and dataUrl. Contains a version in vanilla and one using jquery
//JQUERY version
$(document).ready(function(){
function imgPlaceholders(tc,bgc,datr){
function createPlaceholder(w,h,s){
var canvas = $('<canvas>');
var canvasr = canvas[0];
canvas.attr('width',w).attr('height',h);
var ctx = canvasr.getContext('2d');
ctx.fillStyle = bgc;
ctx.fillRect(0,0,w,h);
var n = w>h?(h/8):(w/8);
ctx.font = n+"px sans-serif";
ctx.fillStyle = tc;
ctx.fillText(s,w/2 - (n/3.5)*s.length,h/2 + (0.866)*s.length);
return canvasr.toDataURL();
}
var pls = [];
$("div["+datr+"],img["+datr+"]").each(function(id,el){
var s = $(el).attr(datr);
var d = s.split('x');
var w = d[0]; var h = d[1];
var pl = (pls[s] == undefined)?(pls[s]=createPlaceholder(w,h,s)):pls[s];
var type = el.nodeName.toLowerCase();
if(type == 'img'){
$(el).attr('src',pl);
}
if(type == 'div'){
$(el).css('background-image',"url("+pl+")");
}
$(el).css('width',w).css('height',h);
});
}
imgPlaceholders("#FFF","#545453","data-img-placeholder");
});
//VANILLA version
function imgPlaceholders(tc,bgc,datr){
function createPlaceholder(w,h,s){
var canvas = document.createElement('canvas');
canvas.setAttribute('width',w);
canvas.setAttribute('height',h);
var ctx = canvas.getContext('2d');
ctx.fillStyle = bgc;
ctx.fillRect(0,0,w,h);
var n = w>h?(h/8):(w/8);
ctx.font = n+"px sans-serif";
ctx.fillStyle = tc;
ctx.fillText(s,w/2 - (n/3.5)*s.length,h/2 + (0.866)*s.length);
return canvas.toDataURL();
}
var pls = [];
var els = document.querySelectorAll("div["+datr+"],img["+datr+"]");
for (var i = 0; i < els.length; i++) {
var el = els[i];
var s = el.getAttribute(datr);
var d = s.split('x');
var w = d[0]; var h = d[1];
var pl = (pls[s] == undefined)?(pls[s]=createPlaceholder(w,h,s)):pls[s];
var type = el.nodeName.toLowerCase();
if(type == 'img'){
el.setAttribute('src',pl)
el.style.width = w;
el.style.height =h;
}
if(type == 'div'){
el.style.backgroundImage= "url("+pl+")";
el.style.width = w;
el.style.height = h;
}
}
}
//Usage
imgPlaceholders("#000","#545453","data-img-placeholder");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment