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. You can use the CSS from another Pen by using it's URL and the proper URL extention.

+ 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

              
                <h1>Texture Tintor</h1>

<input id="fileopen" type="file"/><br>
<span class="color_input"><label>Primary Color: </label><input id="dyecolor1" placeholder="AB01CD" type="text" size="8"><div id="sample1" class="sample"></div>
  <label>(required)</label></span>
<span class="color_input"><label>Secondary Color: </label><input id="dyecolor2" placeholder="AB01CD" type="text" size="8"><div id="sample2" class="sample"></div>
<label>Intensity: </label><input id="mix_rate" placeholder="0.0 or FF" type="text" size="6"></span>
<span class="color_input"><label>Result: </label><input id="dyecolor3" type="text" size="8" readonly><div id="sample3" class="sample"></div></span>
<button id="execute">Tint</button>
<br>
<canvas id="myCanvas" width="160" height="160"></canvas>
<img id="destImg" width="160" height="160"/>
<br>
              
            
!

CSS

              
                
		body {
			background-color: white;
		}
		#myCanvas,#destImg {
			background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAAAAABX3VL4AAAADklEQVQIHWPYXc9QvxsAB2ICdaBJUyUAAAAASUVORK5CYII=");
			background-size: 12px 12px;
			image-rendering: pixelated;
			-ms-interpolation-mode: nearest-neighbor;
			display: inline-block;
			padding: 0px;
		}

#destImg {
  border:0;
  text-decoration:none;
  outline:none;
  image-rendering: pixelated;
}

.sample {
    border: solid 1px #888;
    display: inline-block;
    position: relative;
    padding: 0.6em;
    bottom: -6px;
}

.color_input {
  display: block;
}
.color_input label {
  font-weight: bold;
}

#dyecolor3 {
    border: solid 1px #888;
    padding: 2px;
    background-color: #ccc;
}
              
            
!

JS

              
                $(function(){
  
  /////// Load File /////////////
  $("#fileopen").change(function () {
    
    if(!this.files.length){
      return; //no file selected
    }

    let file = this.files[0];
    let fileRdr = new FileReader();
    fileRdr.onload = function() {
      
      let imgTmp = new Image();
      
      imgTmp.onload = function(){
        
        // initialize canvas
        let canvas = document.querySelector("#myCanvas")
        canvas.setAttribute("width", this.width * 10)
        canvas.setAttribute("height", this.height * 10)
        let ctx = canvas.getContext("2d")
        ctx.imageSmoothingEnabled = false
        ctx.clearRect(0, 0, this.width * 10, this.height * 10)
        
        // stretch draw the loaded image
        ctx.drawImage(imgTmp, 0, 0, this.width, this.height, 0, 0, this.width * 10, this.height * 10)
        
        // store image and filename
        image = imgTmp
        name = file.name.match(/(.*)(?:\.([^.]+$))/)[1]
        
      }
      imgTmp.src = fileRdr.result;
    }
    fileRdr.readAsDataURL(file);
    
  });
  
  /////////// Tint ///////////
  $("#execute").on("click", function(){
    
    if(!image) return // not loaded yet
    
    color = calc_color()
    
    // create temporary canvas
    let canvas = document.createElement("canvas")
    canvas.setAttribute("width", image.width)
    canvas.setAttribute("height", image.height)
    
    // convert image to canvas
    let src_canvas = imageToCanvas(image)
    
    // tint all pixels
    dye_color(canvas, src_canvas, color)
    
    // display stretched image
    let img = document.querySelector("#destImg")
    img.src = canvas.toDataURL("image/png")
    img.setAttribute("width", image.width * 10)
    img.setAttribute("height", image.height * 10)
    
    // not needed anymore
    src_canvas.remove()
    canvas.remove()
    
    // remove last download link
    $("#download").remove()
    
    // append download link
    $("<p/>", {id: "download", text: "Download: "}).append(
		  $('<a id="img_file" href="' + img.src + '" download="' + name + '_tinted.png">' + name + '_tinted.png</a>')
    ).appendTo('body')
    
  })
  
  $("#dyecolor1,#dyecolor2").on("input", function(){
    
    let id = $(this).attr("id").slice(-1)
    
    if($(this).val().length < 6) return
    
    // display sample color
    $("#sample" + id).css("background-color", "#" + $(this).val().slice(-6))
    
    calc_color()
    
  })
  
  $("#dyecolor1,#dyecolor2").change(function(){
    $(this).val($(this).val().slice(-6).toUpperCase())
  })
  
  $("#mix_rate").change(calc_color)
  
  function calc_color(){
    
    let col = $("#dyecolor1").val()
    let col2 = $("#dyecolor2").val()
    let mix = $("#mix_rate").val()
    
    if(!col || col.length < 6) return // not enough length
    if(!isNaN("0x" + mix)){
      if(("0x" + mix) > 1){
        mix = ("0x" + mix) / 0xFF
        $("#mix_rate").val(mix)
      }
    }
    if(isNaN(mix) || mix > 1) { mix = 0 }
    if(!col2 || col2.length < 6) { col2 = "000000"; mix = 0 }
    
    // try to convert text to hex
    col = parseInt("0x" + col.slice(-6))
    col2 = parseInt("0x" + col2.slice(-6))
    
    if(isNaN(col) || isNaN(col2)) return // not valid number
    
    let color = 0
    let rgb1 = toRGB(col);
    let rgb2 = toRGB(col2);
    color = ""
      + hex2(lerp(mix, rgb1.r, rgb2.r))
      + hex2(lerp(mix, rgb1.g, rgb2.g))
      + hex2(lerp(mix, rgb1.b, rgb2.b))
    
    $("#dyecolor3").val(color.toUpperCase())
    $("#sample3").css("background-color", "#" + color)
    
    return "0x" + color
    
  }
  
})

////////////////// MISC FUNCTIONS ////////////////////////

// For texture dyeing
function dye_color(temp_canvas, src_img, dye_color) {
	let w = src_img.width, h = src_img.height;
	temp_canvas.setAttribute("width", w);
	temp_canvas.setAttribute("height", h);
	let temp_ctx = temp_canvas.getContext("2d");
	temp_ctx.clearRect(0, 0, w, h);
	let src_ctx = src_img.getContext("2d");
	let img_data = src_ctx.getImageData(0, 0, w, h);
	for (let x = 0; x < w; x++) {
		for (let y = 0; y < h; y++) {
			let d = (x + y * img_data.width) * 4;
			let data = img_data.data;
			if (data[d + 3] > 0) {
				let new_col = toRGB(dye_color);
				let color = { r: data[d], g: data[d + 1], b: data[d + 2] };
				data[d + 0] = new_col.r * (color.r / 255);
				data[d + 1] = new_col.g * (color.g / 255);
				data[d + 2] = new_col.b * (color.b / 255);
			}
		}
	}
	temp_ctx.putImageData(img_data, 0, 0);
}

function createCanvas(width, height) {
	let canvas = document.createElement("canvas");
	canvas.setAttribute("width", width);
	canvas.setAttribute("height", height);
	canvas.width = width;
	canvas.height = height;
	let context = canvas.getContext('2d');
	context.imageSmoothingEnabled = false;
	return { canvas: canvas, context: context }
}

// IMG->Canvas converter
function imageToCanvas(img) {
	var canvas = createCanvas(img.width, img.height);
	canvas.context.clearRect(0, 0, img.width, img.height);
	canvas.context.drawImage(img, 0, 0, img.width, img.height, 0, 0, img.width, img.height);
	return canvas.canvas;
}
function toRGB(color){
    let rgb = {}
    rgb.r = (color >> 16) & 0xFF
    rgb.g = (color >> 8) & 0xFF
    rgb.b = color & 0xFF
    return rgb
}

function lerp(rate, begin, end) {
	return begin + rate * (end - begin)
}

function hex2(val){
  return ("00" + Math.floor(val).toString(16)).slice(-2)
}
              
            
!
999px

Console