1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
| const hexColorPairs = [ ["#ff0000", "#0000ff"], ["#000000", "#ffffff"], ];
const rgbColorPairs = hexColorPairs.map((hexColorPair) => { return hexColorPair.map((hex) => convertHextoRgb(hex)); });
const rgbDiffPairs = rgbColorPairs.map((rgbColorPair, i) => { return rgbColorPair.map((rgbColor, j) => { if (i === rgbColorPairs.length - 1) { return getColorDiff(rgbColor, rgbColorPairs[0][j]); } else { return getColorDiff(rgbColor, rgbColorPairs[i + 1][j]); } }); });
let currentPairIndex = 0; let paintColorPair = rgbColorPairs[currentPairIndex];
const canvas = document.querySelector("canvas"); const ctx = canvas.getContext("2d");
canvas.width = 600; canvas.height = 300;
function makeGradient() { ctx.clearRect(0, 0, canvas.width, canvas.height); const gradient = ctx.createLinearGradient(0, 0, canvas.width, canvas.height);
paintColorPair.forEach((paintColor, index) => { gradient.addColorStop( index === 0 ? 0 : 1, `rgb(${paintColor[0]}, ${paintColor[1]}, ${paintColor[2]})` ); });
ctx.fillStyle = gradient; ctx.fillRect(0, 0, canvas.width, canvas.height); } makeGradient();
const duration = 5000;
let previousTimeStamp = 0; let process = 0; function animateColor(timestamp) { process = process + (timestamp - previousTimeStamp); previousTimeStamp = timestamp;
const progressPercent = ((process / duration) * 100).toFixed(2);
paintColorPair = rgbColorPairs[currentPairIndex].map((rgbColor, i) => { return rgbColor.map((item, j) => { return ( item + Math.round( (rgbDiffPairs[currentPairIndex][i][j] / 100) * progressPercent ) ); }); });
makeGradient();
if (progressPercent < 100) { requestAnimationFrame(animateColor); } else { process = 0;
if (currentPairIndex === rgbColorPairs.length - 1) { currentPairIndex = 0; } else { currentPairIndex++; }
requestAnimationFrame(animateColor); } }
requestAnimationFrame(animateColor);
|