JSFiddle - React, Tailwind, and code Playground

by m1erickson

HTML

<canvas id="canvas" width=300 height=300></canvas>

CSS

body{ background-color: ivory; }
canvas{border:1px solid red;}

JavaScript

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");

// draw a red rect on the canvas
ctx.fillStyle="red";
ctx.fillRect(50,50,75,40);

// get the canvas imageData
var imageData=ctx.getImageData(0,0,canvas.width,canvas.height);
var data=imageData.data;

// replace any red pixels with green pixels
for(var i=0;i<data.length;i+=4){
    if(data[i]>250){
        data[i]=0;
        data[i+1]=255;
    }
}

// clear the canvas
ctx.clearRect(0,0,canvas.width,canvas.height);

// create a temporary canvas
var tempCanvas=document.createElement("canvas");
var tempCtx=tempCanvas.getContext("2d");

// set the temp canvas size == the canvas size
tempCanvas.width=canvas.width;
tempCanvas.height=canvas.height;

// put the modified pixels on the temp canvas
tempCtx.putImageData(imageData,0,0);

// use the tempCanvas.toDataURL to create an img object
var img=new Image();
img.onload=function(){
    // drawImage the img on the canvas
    ctx.drawImage(img,0,0);
}
img.src=tempCanvas.toDataURL();