Skip to content

Instantly share code, notes, and snippets.

@andyfitz
Created November 1, 2021 13:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andyfitz/bf197e9cd89deb8df583bb9b17c09852 to your computer and use it in GitHub Desktop.
Save andyfitz/bf197e9cd89deb8df583bb9b17c09852 to your computer and use it in GitHub Desktop.
Creating Duotone Filter SVG images
function hexToRgb(hex) {
// Expand shorthand form (e.g. "FA7") to full form (e.g. "FFAA77")
var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
hex = hex.replace(shorthandRegex, function (m, r, g, b) {
return r + r + g + g + b + b;
});
var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ?{
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16)
}
: null;
}
function drawDuotone() {
image = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
image.setAttribute("viewBox", "0 0 100 100");
image.setAttribute("preserveAspectRatio", "xMidYMid slice");
photo = document.createElementNS("http://www.w3.org/2000/svg", "image");
photo.setAttribute("href", randomPhoto);
photo.setAttribute("style", "filter: url(#o-duo);");
photo.setAttribute("width", "100");
photo.setAttribute("height", "100");
photo.setAttribute("preserveAspectRatio", "xMidYMid slice");
photo.innerHTML += '<defs><filter id="o-duo">' +
'<feColorMatrix type="saturate" values="0"/>' +
'<feComponentTransfer color-interpolation-filters="sRGB" >' +
' <feFuncR id="randomR" type="table" tableValues="' + rRed + '" /> ' +
' <feFuncG id="randomG" type="table" tableValues="' + rGreen + '" />' +
' <feFuncB id="randomB" type="table" tableValues="' + rBlue + '" />' +
' <feFuncA type="table" tableValues="0 1"></feFuncA> ' +
'</feComponentTransfer></filter></defs>';
var stage = document.querySelector('body');
stage.appendChild(image);
image.appendChild(photo);
}
drawDuotone();
let randomLight = lightColors[Math.floor(Math.random() * lightColors.length)];
let randomDark = darkColors[Math.floor(Math.random() * darkColors.length)];
let rRed = hexToRgb(randomDark).r / 255 + " " + hexToRgb(randomLight).r / 255;
let rGreen = hexToRgb(randomDark).g / 255 + " " + hexToRgb(randomLight).g / 255;
let rBlue = hexToRgb(randomDark).b / 255 + " " + hexToRgb(randomLight).b / 255;
var searchTerm = "ocean";
let randomPhoto = "https://source.unsplash.com/daily?" + searchTerm + "?" + Math.floor(Math.random() * 1000);
function removeAll() { stage.innerHTML = "";}
document.addEventListener("click", function () { removeAll(); drawDuotone();});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment