JSFiddle - React, Tailwind, and code Playground

by robert_schutt

HTML

<canvas width="600" height="400" style="border: 1px solid red;" id="cnv">no canvas!</canvas>
<br>
<!-- canvas width="600" height="400" style="border: 1px solid red;" id="cnv2">no canvas!</canvas>
<br -->
<input type="range" min="1" max="100" value="50" id="opac" onchange="modX.setNoise(this.value/100)">

JavaScript

window.modX = (function(){
var thecanvas = document.getElementById('cnv');
var thecontext = thecanvas.getContext('2d');
//var thecanvas2 = document.getElementById('cnv2');
//var thecontext2 = thecanvas2.getContext('2d');
return {
thecanvas:thecanvas,
thecontext:thecontext,
//thecanvas2:thecanvas2,
//thecontext2:thecontext2,
iteration:0,
setNoise:function(opacity){
this.thecontext.fillStyle='yellow';
this.thecontext.fillRect(0,0,this.thecanvas.width,this.thecanvas.height);
this.thecontext.moveTo(0,0);
this.thecontext.lineTo(600,400);
this.thecontext.moveTo(0,400);
this.thecontext.lineTo(600,0);
this.thecontext.lineWidth=5;
this.thecontext.strokeStyle='white';
this.thecontext.stroke();

    opacity = opacity || .2;
    
    var iPos, imgData = this.thecontext.getImageData(0,0,this.thecanvas.width,this.thecanvas.height);
    for (var x = 0; x < this.thecanvas.width; x++ ) {
        for (var y = 0; y < this.thecanvas.height; y++ ) {
          let number = Math.floor( Math.random() * 60 );
          if (number > 50) { // threshold for less noise
           iPos = (y * this.thecanvas.width + x) * 4; // 4 bytes per pixel (rgba)
           imgData.data[iPos  ] = Math.floor(imgData.data[iPos  ] * (1 - opacity) + number * opacity);
           imgData.data[iPos+1] = Math.floor(imgData.data[iPos+1] * (1 - opacity) + number * opacity);
           imgData.data[iPos+2] = Math.floor(imgData.data[iPos+2] * (1 - opacity) + number * opacity);
           imgData.data[iPos+3] = 255;
          }
        }
    }
    this.thecontext.putImageData(imgData,0,0);
    
		/*setTimeout((function(this_iteration, this_thecanvas, this_thecontext){
      return function(){
this_thecontext.fillStyle='yellow';
this_thecontext.fillRect(0,0,this_thecanvas.width,this_thecanvas.height);
this_thecontext.moveTo(0,0);
this_thecontext.lineTo(600,400);
this_thecontext.moveTo(0,400);
this_thecontext.lineTo(600,0);
this_thecontext.lineWidth=5;
this_thecontext.strokeStyle='white';
this_thecontext.stroke();
    ...