Created
May 6, 2023 16:31
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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