Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function hexToRgb(hex) {
- 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 rgbToHex(color) {
- return "#" + ((1 << 24) + (Math.trunc(color.r) << 16) + (Math.trunc(color.g) << 8) + Math.trunc(color.b)).toString(16).slice(1);
- }
- function interpolate(from, to, influence) {
- if (influence < 0)
- influence = 0;
- if (influence > 1)
- influence = 1;
- return from + (to - from) * influence;
- }
- function interpolateRgb(from, to, influence) {
- if (!from || !to)
- return null;
- return {
- r: interpolate(from.r, to.r, influence),
- g: interpolate(from.g, to.g, influence),
- b: interpolate(from.b, to.b, influence)
- }
- }
- function rgbToString(color) {
- return `(${color.r}, ${color.g}, ${color.b})`;
- }
- function colorizeSelection(from, to) {
- let rgbFrom = hexToRgb(from);
- let rgbTo = hexToRgb(to);
- let selection = DocumentApp.getActiveDocument().getSelection();
- if (selection) {
- var elements = selection.getRangeElements();
- for (var i = 0; i < elements.length; i++) {
- var element = elements[i];
- if (element.getElement().editAsText) {
- var text = element.getElement().editAsText();
- let fromPosition = element.getStartOffset();
- let toPosition = element.getEndOffsetInclusive();
- let difference = toPosition - fromPosition + 1;
- for (var j = fromPosition; j <= toPosition; j++) {
- let color = rgbToHex(interpolateRgb(rgbFrom, rgbTo, (j - fromPosition) / difference));
- text.setForegroundColor(j, j, color);
- }
- }
- }
- }
- }
- function openSidebar() {
- DocumentApp.getUi().showSidebar(HtmlService.createHtmlOutputFromFile('Index'));
- }
- function onOpen() {
- DocumentApp.getUi().createMenu("Colorize").addItem("Run", "openSidebar").addToUi();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement