Created
February 23, 2023 14:05
-
-
Save motsu0/fa5af9dce03c365996330508409b5a94 to your computer and use it in GitHub Desktop.
This file contains 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
/*! | |
* bg-color-checkered.js v1.0 | |
* | |
* Copyright (c) 2023 motsu | |
* | |
* Released under the MIT license. | |
* see https://opensource.org/licenses/MIT | |
*/ | |
class bgColorCheckered{ | |
constructor(element, args){ | |
const color_rc = (()=>{ | |
if(!Array.isArray(args)) return [['#ffffff']]; | |
for(let i=0;i<args.length;i++){ | |
if(!Array.isArray(args[i])) return [['#ffffff']]; | |
for(let j=0;j<args[i].length;j++){ | |
if(typeof args[i][j]!=='string') return [['#ffffff']]; | |
} | |
} | |
return args; | |
})(); | |
const width_el = element.clientWidth; | |
const height_el = element.clientHeight; | |
const el_canvas = document.createElement('canvas'); | |
el_canvas.width = width_el; | |
el_canvas.height = height_el; | |
const ctx = el_canvas.getContext('2d'); | |
const num_row = color_rc.length; | |
const height_unit = Math.round(height_el / num_row); | |
const array_height_unit = (new Array(num_row)).fill(height_unit); | |
array_height_unit[num_row-1] += height_el - (height_unit * num_row); | |
for(let r=0;r<color_rc.length;r++){ | |
const num_column = color_rc[r].length; | |
const width_unit = Math.round(width_el / num_column); | |
const array_width_unit = (new Array(num_column)).fill(width_unit); | |
array_width_unit[num_column-1] += width_el - (width_unit * num_column); | |
for(let c=0;c<num_column;c++){ | |
ctx.fillStyle = color_rc[r][c]; | |
ctx.fillRect(c*width_unit, r*height_unit, array_width_unit[c], array_height_unit[r]); | |
} | |
} | |
const dataURL = el_canvas.toDataURL('image/jpeg', 1); | |
element.style.backgroundImage = `url(${dataURL})`; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment