Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <svg width="1" height="1" style="position: absolute;top:0;right:0;">
  <defs xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
    <symbol id="rangeControl">
      <path fill="gray" d="M5,0 l5,5 v10 h-10 v-10 l5,-5"></path>
    </symbol>
  </defs>
</svg>
<div id="levelsUI" class="levels_ui noselect">
  <div class="levels_ui--imageContainer">
    
    <div style="position:relative; top:21px;float:right">
      
    HISTOGRAM
    </div>
    <svg class="levels_ui--svgContainer" width="320" height="280" viewbox="0 0 320 280" preserveAspectRation="xMidYMid meet" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
      <defs class="levels_ui--svgDefs"></defs>
      <image class="levels_ui--filteredImage" x="0" y="0" width="320" height="280" />
    </svg>
    <canvas class="levels_ui--canvasContainer" width="320" height="280"></canvas>
  </div>
  <!--
        -->
  <div class="levels_ui--panelContainer">
    <div class="levels_ui--channels-buttons">
      <button class="levels_ui--channels-button">RGB</button>
      <button class="levels_ui--channels-button">R</button>
      <button class="levels_ui--channels-button">G</button>
      <button class="levels_ui--channels-button">B</button>
      <button class="levels_ui--channels-button">A</button>
    </div>
    <canvas class="levels_ui--histogram" width="320" height="60"></canvas>
    <div class="levels_ui--range-selector input" style="width:320px;height:40px;position:relative;margin-bottom:10px">
      <svg class="levels_ui--range-selector__thumb inputBlack" width="20" height="30" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
        <use xlink:href="#rangeControl" style="pointer-events:none">
      </svg>
      <svg class="levels_ui--range-selector__thumb gamma" width="20" height="30" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
        <use xlink:href="#rangeControl" style="pointer-events:none">
      </svg>
      <svg class="levels_ui--range-selector__thumb inputWhite" style="left:315px" width="20" height="30" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
        <use xlink:href="#rangeControl" style="pointer-events:none">
      </svg>
    </div>
    <svg width="320" height="10">
      <defs>
        <linearGradient id="grad1" x1="0%" y1="0%" x2="100%" y2="0%">
          <stop offset="0%" style="stop-color:rgb(0,0,0);stop-opacity:1" />
          <stop offset="100%" style="stop-color:rgb(255,255,255);stop-opacity:1" />
        </linearGradient>
      </defs>
      <rect width="320" height="10" fill="url(#grad1)">
    </svg>
    <div class="levels_ui--range-selector output" style="width:320px;height:20px;position:relative;margin-bottom:10px">
      <svg class="levels_ui--range-selector__thumb outputBlack" width="20" height="30" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
        <use xlink:href="#rangeControl" style="pointer-events:none">
      </svg>
      <svg class="levels_ui--range-selector__thumb outputWhite" style="left:315px" width="20" height="30" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
        <use xlink:href="#rangeControl" style="pointer-events:none">
      </svg>
    </div>
    <div>
      <form>
        <label for="fileInput" style="background-color:white; width: 100%; padding: 2px;display: block; border-radius: 2px; text-align: center; cursor: pointer;">Load a File...</label>
        <input id="fileInput" class="levels_ui--fileInput" type="file" style="display: none">
      </form>
    </div>
  </div>
</div>
              
            
!

CSS

              
                
body{
    background-color: #222;   
/*   width:100%; */
  display:flex;
  justify-content:center;
/*   margin-left:auto; */
/*   margin-right:auto; */
}
.noselect {
  -webkit-touch-callout: none; /* iOS Safari */
    -webkit-user-select: none; /* Chrome/Safari/Opera */
     -khtml-user-select: none; /* Konqueror */
       -moz-user-select: none; /* Firefox */
        -ms-user-select: none; /* Internet Explorer/Edge */
            user-select: none; /* Non-prefixed version, currently
                                  not supported by any browser */
}
.levels_ui {
    font-family: Arial, Helvetica, sans-serif;
    box-sizing: border-box;
    width: 682px;
    border: 2px solid gray;
    margin-bottom: 10px;
    padding: 0 2px;
    background-color: #e0e0e0;
}

.levels_ui--imageContainer {
    width: 320px;
    display: inline-block;
    vertical-align: middle;
    margin-right: 20px;
}

.levels_ui--panelContainer {
    width: 320px;
    display: inline-block;
    vertical-align: top;
    margin-top:10px;
}

.levels_ui--channels-buttons{
    padding: 10px 0;
    width: 320px;
    font-size: 0;
}
.levels_ui--channels-button {
    border: none;
    background-color: #ccc;
    color: #000;
    padding: 4px 2px;
    width: 18%;
    cursor: pointer;
    margin-right: 2%;
    border-radius: 2px;
    font-size: 10px;
    border-bottom: 3px solid #fff;
    border-right: 3px solid #fff;
    display: inline-block;
    vertical-align: top;
    text-align: center;
    box-sizing: border-box;
}
.levels_ui--channels-button:hover {
    background-color: #fff;
    border-bottom: 3px solid #ccc;
    border-right: 3px solid #ccc;
}
.levels_ui--channels-button:focus {
    outline: none;
}
.levels_ui--channels-button__selected{
    background-color: #fff;
    color: #666;
    border-bottom: 3px solid #24B9CB;
    border-right: 3px solid #24B9CB;
}
.levels_ui--channels-button__selected:hover{
    background-color: #fff;
    color: #666;
    border-bottom: 3px solid #24B9CB;
    border-right: 3px solid #24B9CB;
}
.levels_uichannels-button:hover{
    background-color: #24B9CB;
}
.levels_uichannels-button__selected:hover{

    background-color: #55DCEC;
    color: #666;
}
.levels_ui--histogram {
    width: 320px;
    height: 100px;
    display: block;
}
.levels_ui--range-selector{
    width: 20px;
    height: 20px;
}
.levels_ui--range-selector__thumb{
    position: absolute;
    top:0;
    left:-5px;
}


/* MULTITONE */
.levels_ui--channels-button__multitone{
    width: 48%;
    font-size: 12px;
}

.levels_ui--color-list{
    padding: 0;
    margin: 0;
}

.levels_ui--color-list--element{
    width: 20px;
    height: 20px;
    display: inline-block;
    border: 2px solid black;
    border-radius: 2px;
    margin-right: 2px;
}

.levels_ui--toneName{
    font-size: 14px;
    text-align: center;
    padding: 4px 0;
    margin: 0 0 4px 0;
    font-weight: normal;
    color: #fff;
    background-color: #24B9CB;
}
              
            
!

JS

              
                var levelsControllerFactory = (function() {

  var channels = ['rgb', 'r', 'g', 'b', 'a'];
  var svgNS = "http://www.w3.org/2000/svg";
  var xlinkNS = 'http://www.w3.org/1999/xlink';

  function init() {
    this._createColorLevels();
    this._attachEvents();
    this._initiateDisplayMode();
  }

  function _initiateDisplayMode() {
    if (this._type === 'svg') {
      this._domElement.getElementsByClassName('levels_ui--canvasContainer')[0].style.display = 'none';
    } else {
      this._domElement.getElementsByClassName('levels_ui--svgContainer')[0].style.display = 'none';
    }
    //levels_ui--svgContainer
  }

  function _createColorLevels() {
    var factory = this._type === 'svg' ? svgLevelsFactory : canvasLevelsFactory;
    this.data = {
      currentChannel: 'rgb',
      levels: {
        rgb: {
          levels: factory('rgb')
        },
        r: {
          levels: factory('r')
        },
        g: {
          levels: factory('g')
        },
        b: {
          levels: factory('b')
        },
        a: {
          levels: factory('a')
        }
      }
    }

    if (this._type === 'svg') {
      this.data.levels.rgb.levels.compose();
      this.data.levels.r.levels.compose();
      this.data.levels.g.levels.compose();
      this.data.levels.b.levels.compose();
      this.data.levels.a.levels.compose();
      var defs = this._domElement.getElementsByClassName('levels_ui--svgDefs')[0];
      defs.appendChild(this.data.levels.rgb.levels.filter);
      defs.appendChild(this.data.levels.r.levels.filter);
      defs.appendChild(this.data.levels.g.levels.filter);
      defs.appendChild(this.data.levels.b.levels.filter);
      defs.appendChild(this.data.levels.a.levels.filter);
    }
  }

  function _updateHistogram() {

    var cvs = this.canvasHistogram;
    var data = this._histogramData;
    w = cvs.width;
    h = cvs.height;

    cvs.width = cvs.width;
    var ctx = cvs.getContext('2d');
    var i;
    var barHeight;
    if (this.data.currentChannel === 0 || this.data.currentChannel === 1) {
      // Red
      ctx.fillStyle = '#ff0000';
      ctx.beginPath();
      for (i = 0, len = 256; i < len; i += 1) {
        barHeight = (data.r[i] / data.maxValues.r) * h;
        ctx.fillRect(w / 256 * i, h - barHeight, 1, barHeight);
      }
      ctx.fill();
      ctx.closePath();
    }
    if (this.data.currentChannel === 0) {
      ctx.globalCompositeOperation = 'lighten';
    }
    if (this.data.currentChannel === 0 || this.data.currentChannel === 2) {
      // Green
      ctx.fillStyle = '#00ff00';
      ctx.beginPath();
      for (i = 0, len = 256; i < len; i += 1) {
        barHeight = (data.g[i] / data.maxValues.g) * h;
        ctx.fillRect(w / 256 * i, h - barHeight, 1, barHeight);
      }
      ctx.fill();
      ctx.closePath();
      //
    }
    if (this.data.currentChannel === 0 || this.data.currentChannel === 3) {
      // Blue
      ctx.fillStyle = '#0000ff';
      ctx.beginPath();
      for (i = 0, len = 256; i < len; i += 1) {
        barHeight = (data.b[i] / data.maxValues.b) * h;
        ctx.fillRect(w / 256 * i, h - barHeight, 1, barHeight);
      }
      ctx.fill();
      ctx.closePath();
    }
    if (this.data.currentChannel === 4) {
      // Alpha
      ctx.fillStyle = '#cccccc';
      ctx.beginPath();
      for (i = 0, len = 256; i < len; i += 1) {
        barHeight = (data.a[i] / data.maxValues.a) * h;
        ctx.fillRect(w / 256 * i, h - barHeight, 1, barHeight);
      }
      ctx.fill();
      ctx.closePath();
    }

  }

  function _buildHistogramData(cvs) {
    var ctx = cvs.getContext('2d');
    var imageData = ctx.getImageData(0, 0, cvs.width, cvs.height).data;
    this._histogramData = canvasHistogram(imageData);
    this.data.currentChannel = -1;
    this._channelChange(0);
  }

  function _channelChange(index) {
    if (this.data.currentChannel === index) {
      return;
    }
    if (this._type !== 'svg' && this.data.levels[channels[this.data.currentChannel]]) {
      this.data.levels[channels[this.data.currentChannel]].levels.resetCanvasData();
      this.data.levels[channels[this.data.currentChannel]].levels.destroyCanvasData();
    }
    this.data.currentChannel = index;
    if (this._type !== 'svg') {
      this.data.levels[channels[this.data.currentChannel]].levels.canvas = this.canvasElement;
    }
    this.channelButtons.setButton(index);
    this._updateHistogram();
    this.levelHandlers.setValues(this.data.levels[channels[this.data.currentChannel]].levels.values);
  }

  function _levelsChange(values) {
    var colorOb = this.data.levels[channels[this.data.currentChannel]];
    colorOb.levels.setLevelValues(values);
    colorOb.levels.compose();
    if (this._type === 'svg') {
      this.filteredImage.setAttribute('filter', 'url(#' + colorOb.levels.id + ')');
    }
  }

  function _attachEvents() {
    this.channelButtons = this._setupChannelButtons();
    this.channelButtons.onChange = this._channelChange.bind(this);
    this.channelButtons.init(this._domElement);
    this.levelHandlers = this._setupLevelHandlers();
    this.levelHandlers.onChange = this._levelsChange.bind(this);
    this.levelHandlers.init(this._domElement);
    var fileInput = this._domElement.getElementsByClassName('levels_ui--fileInput')[0];
    fileInput.onchange = function(evt) {
      var tgt = evt.target || window.event.srcElement,
        files = tgt.files;
      // FileReader support
      if (FileReader && files && files.length) {
        var fr = new FileReader();
        fr.onload = function() {
          this.loadImage(fr.result);
        }.bind(this)
        fr.readAsDataURL(files[0]);
      }
    }.bind(this);
  }

  function _setupChannelButtons() {
    function handleChannelClick(index) {
      if (this.onChange) {
        this.onChange(index);
      }
    }

    function setupButtonListener(elem, index) {
      elem.addEventListener('click', function() {
        this.handleChannelClick(index)
      }.bind(this))
    }

    function setButton(index) {
      var i, len = this.buttons.length;
      for (i = 0; i < len; i += 1) {
        if (i === index) {
          this.buttons[i].className = 'levels_ui--channels-button levels_ui--channels-button__selected';
        } else {
          this.buttons[i].className = 'levels_ui--channels-button';
        }
      }
    }

    function init(domElement) {
      this.buttons = domElement.getElementsByClassName('levels_ui--channels-button');
      var i, len = this.buttons.length;
      for (i = 0; i < len; i += 1) {
        this.setupButtonListener(this.buttons[i], i);
      }
    }

    var ob = {
      init: init,
      setButton: setButton,
      setupButtonListener: setupButtonListener,
      handleChannelClick: handleChannelClick
    };
    return ob;
  }

  function _setupLevelHandlers() {

		var inputBlackHandler, inputWhiteHandler, outputBlackHandler, outputWhiteHandler, gammaHandler, inputContainer, outputContainer;
		var currentHandler, currentContainer, currentKey;
		var gammaValue = 0;

		var currentPositions = {
			inputBlack: -5,
			inputWhite: 315,
			gamma: 155,
			outputBlack: -5,
			outputWhite: 315
		}

		function getMarginsByKey(key) {
			if(key === 'gamma') {
				return {
					min: currentPositions.inputBlack,
					max: currentPositions.inputWhite
				}
			} else if(key === 'inputBlack') {
				return {
					min: -5,
					max: currentPositions.inputWhite
				}
			} else if(key === 'inputWhite') {
				return {
					min: currentPositions.inputBlack,
					max: 315
				}
			} else {
				return {
					min: -5,
					max: 315
				}
			}
		}

		function updateGammaPosition(key) {
			if(key === 'inputBlack' || key === 'inputWhite') {
				var inputDelta = currentPositions.inputWhite - currentPositions.inputBlack;
				if(gammaValue < 1) {
					currentPositions.gamma = inputDelta / 2 + currentPositions.inputBlack + (1-gammaValue) * (inputDelta / 2);
				} else if(gammaValue > 1) {
					currentPositions.gamma = currentPositions.inputBlack + inputDelta/2 - (((gammaValue - 1) / 4)) * inputDelta/2;
				} else {
					currentPositions.gamma = currentPositions.inputBlack + inputDelta/2;
				}
				gammaHandler.style.left = currentPositions.gamma + 'px';
			}
		}

		var documentMoveHandler = function(ev) {
			var margins = getMarginsByKey(currentKey);
			currentPositions[currentKey] = Math.max(margins.min, Math.min(margins.max, (ev.pageX - 2.5) - currentContainer.offsetLeft)); 
			currentHandler.style.left = currentPositions[currentKey] + 'px';
			updateGammaPosition(currentKey);
		}.bind(this)

		var documentUpHandler = function(ev) {
			document.removeEventListener('mousemove', documentMoveHandler);
			document.removeEventListener('mouseup', documentUpHandler);
			handleChange();
		}.bind(this)

		function handleMouseDown(ev) {
			if(ev.target === inputBlackHandler || ev.target === inputWhiteHandler) {
				currentHandler = ev.target;
				currentContainer = inputContainer;
				if(ev.target === inputBlackHandler) {
					currentKey = 'inputBlack';
				} else {
					currentKey = 'inputWhite';
				}
				document.addEventListener('mousemove', documentMoveHandler);
				document.addEventListener('mouseup', documentUpHandler);
			} else if(ev.target === outputBlackHandler || ev.target === outputWhiteHandler || ev.target === gammaHandler) {
				currentHandler = ev.target;
				currentContainer = inputContainer;
				if(ev.target === outputBlackHandler) {
					currentKey = 'outputBlack';
				} else if(ev.target === outputWhiteHandler) {
					currentKey = 'outputWhite';
				} else {
					currentKey = 'gamma';
				}
				document.addEventListener('mousemove', documentMoveHandler);
				document.addEventListener('mouseup', documentUpHandler);
			}
		}

		function handleChange() {
			if(ob.onChange) {
				var values = {
					inputBlack: ((currentPositions.inputBlack + 5)/320) * 255,
					inputWhite: ((currentPositions.inputWhite + 5)/320) * 255,
					outputBlack: ((currentPositions.outputBlack + 5)/320) * 255,
					outputWhite: ((currentPositions.outputWhite + 5)/320) * 255
				}
				var inputDelta = currentPositions.inputWhite - currentPositions.inputBlack;
				if(currentPositions.gamma < currentPositions.inputBlack + inputDelta / 2) {
					values.gamma = 1 + (1 - (currentPositions.gamma - currentPositions.inputBlack) / (inputDelta / 2)) * 4;
				} else if(currentPositions.gamma > currentPositions.inputBlack + inputDelta/2) {
					values.gamma = 1 - ((currentPositions.gamma - currentPositions.inputBlack - inputDelta/2) / inputDelta) * 2;
				} else {
					values.gamma = 1;
				}
				gammaValue = values.gamma;
				ob.onChange(values);
			}
		}

		function setValues(values) {
			currentPositions.inputBlack = -5 + (values.inputBlack/255)*320;
			currentPositions.inputWhite = -5 + (values.inputWhite/255)*320;
			var inputDelta = currentPositions.inputWhite - currentPositions.inputBlack;
			if(values.gamma < 1) {
				currentPositions.gamma = inputDelta / 2 + currentPositions.inputBlack + (1-values.gamma) * (inputDelta / 2);
			} else if(values.gamma > 1) {
				currentPositions.gamma = currentPositions.inputBlack + inputDelta/2 - (((values.gamma - 1) / 4)) * inputDelta/2;
			} else {
				currentPositions.gamma = currentPositions.inputBlack + inputDelta/2;
			}
			gammaValue = values.gamma;
			currentPositions.outputBlack = -5 + (values.outputBlack/255)*320;
			currentPositions.outputWhite = -5 + (values.outputWhite/255)*320;
			this.updatePositions();
			handleChange();
		}

		function updatePositions() {
			inputBlackHandler.style.left = currentPositions.inputBlack + 'px';
			inputWhiteHandler.style.left = currentPositions.inputWhite + 'px';
			outputBlackHandler.style.left = currentPositions.outputBlack + 'px';
			outputWhiteHandler.style.left = currentPositions.outputWhite + 'px';
			gammaHandler.style.left = currentPositions.gamma + 'px';
		}

		function init(domElement) {
			
			inputBlackHandler = domElement.getElementsByClassName('inputBlack')[0];
			inputWhiteHandler = domElement.getElementsByClassName('inputWhite')[0];
			gammaHandler = domElement.getElementsByClassName('gamma')[0];
			outputBlackHandler = domElement.getElementsByClassName('outputBlack')[0];
			outputWhiteHandler = domElement.getElementsByClassName('outputWhite')[0];
			inputContainer = domElement.getElementsByClassName('input')[0];
			inputContainer.addEventListener('mousedown', handleMouseDown);
			outputContainer = domElement.getElementsByClassName('output')[0];
			outputContainer.addEventListener('mousedown', handleMouseDown);
			this.updatePositions();
		}

		var ob = {
			init: init,
			setValues: setValues,
			updatePositions: updatePositions
		}

		return ob;
	}

  function _imageLoaded() {
    var cvs = document.createElement('canvas')
    cvs.width = this.image.width;
    cvs.height = this.image.height;
    var ctx = cvs.getContext('2d');
    ctx.drawImage(this.image, 0, 0);
    if (this._type !== 'svg') {
      var imgW = cvs.width,
        imgH = cvs.height;
      var canvasW = this.canvasElement.width,
        canvasH = this.canvasElement.height;
      var imgRel = imgW / imgH,
        canvasRel = canvasW / canvasH;
      var finalW, finalH, offsetX = 0,
        offsetY = 0;
      if (imgRel > canvasRel) {
        finalW = canvasW;
        finalH = imgH * canvasW / imgW;
        offsetY = (canvasH - finalH) / 2;
      } else {
        finalH = canvasH;
        finalW = imgW * canvasH / imgH;
        offsetX = (canvasW - finalW) / 2;
      }
      this.canvasElement.width = this.canvasElement.width;
      var canvasElementCtx = this.canvasElement.getContext('2d');
      canvasElementCtx.drawImage(cvs, 0, 0, imgW, imgH, offsetX, offsetY, finalW, finalH);
    }
    this._buildHistogramData(cvs);
  }

  function loadImage(path) {
    if (!this.image) {
      this.image = document.createElement('img');
      this.image.crossOrigin = "Anonymous";
      this.image.addEventListener('load', this._imageLoaded.bind(this));
    }
    this.image.src = path;
    if (this._type === 'svg') {
      this.filteredImage.setAttributeNS(xlinkNS, 'href', path);
    }
  }

  var proto = {
    loadImage: loadImage,
    _imageLoaded: _imageLoaded,
    _init: init,
    _initiateDisplayMode: _initiateDisplayMode,
    _attachEvents: _attachEvents,
    _setupChannelButtons: _setupChannelButtons,
    _setupLevelHandlers: _setupLevelHandlers,
    _channelChange: _channelChange,
    _levelsChange: _levelsChange,
    _updateHistogram: _updateHistogram,
    _buildHistogramData: _buildHistogramData,
    _createColorLevels: _createColorLevels
  }

  return function(domElement, type, w, h) {
    var instance = Object.create(proto, {
      _width: {
        value: w || 320
      },
      _height: {
        value: h || 200
      },
      _type: {
        value: type || 'svg'
      },
      _domElement: {
        value: domElement
      },
      image: {
        value: null,
        writable: true
      },
      _histogramData: {
        value: null,
        writable: true
      },
      filteredImage: {
        value: domElement.getElementsByClassName('levels_ui--filteredImage')[0]
      },
      canvasElement: {
        value: domElement.getElementsByClassName('levels_ui--canvasContainer')[0]
      },
      canvasHistogram: {
        value: domElement.getElementsByClassName('levels_ui--histogram')[0]
      }
    });
    instance._init();
    return instance;
  }

}())

var levelsUI = document.getElementById('levelsUI');
var levelsController = levelsControllerFactory(levelsUI, 'svg');
// levelsController.loadImage('https://s3-us-west-2.amazonaws.com/s.cdpn.io/278239/her_lau_small.jpg');
levelsController.loadImage('https://assets.codepen.io/1712301/IMG_1969-1_Resized_2048_px.jpg?width=320');
              
            
!
999px

Console