Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save olivsinz/d78afc400b0350cde42203d10359f9f3 to your computer and use it in GitHub Desktop.
Save olivsinz/d78afc400b0350cde42203d10359f9f3 to your computer and use it in GitHub Desktop.
Apply background on product page (main-product.liquid) with main product image - Shopify
<div id="section-with-background">
<!-- product page section to apply background color to -->
</div>
<script>
document.addEventListener('DOMContentLoaded', (event) => {
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
const image = new Image();
image.crossOrigin = "Anonymous";
let product_featured_image = {{ product.featured_image | json }}
image.src = product_featured_image;
image.onload = () => {
canvas.width = image.width;
canvas.height = image.height;
context.drawImage(image, 0, 0, 1, 1);
let calculatedColor = context.getImageData(0, 0, 1, 1).data.join(',');
const colorIndividualValues = calculatedColor.split(',');
let rgbFormValue = colorIndividualValues[0] + "," + colorIndividualValues[1] + "," + colorIndividualValues[2];
//if dominant color is white and main background color is white, apply a darker background for highlight
if (colorIndividualValues[0] >= 240 && colorIndividualValues[1] >= 240 && colorIndividualValues[2] >= 240) {
rgbFormValue = "0,0,0";
}
document.querySelector('#section-with-background').style.backgroundColor = `rgba(${rgbFormValue},0.18)`
};
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment