JSFiddle - React, Tailwind, and code Playground

by loktar

HTML

<canvas id="canvas" width="100" height="100"></canvas>
<br/>
<input type="button" id="modify" value="Modify"/>
<input type="button" id="save" value="Save"/>
<input type="button" id="restore" value="Restore"/>
<input type="button" id="clear" value="Clear Canvas"/>

JavaScript

// Unimportant just for example
var modifyBtn = document.getElementById('modify'),
    saveBtn = document.getElementById('save'),
    restoreBtn = document.getElementById('restore'),
    clearBtn = document.getElementById('clear');

modifyBtn.onclick = modify;
saveBtn.onclick = save;
restoreBtn.onclick = restore;
clearBtn.onclick = clear;

// Setup our vars, make a new image to store the canvas data
var canvas = document.getElementById("canvas"),
    ctx = canvas.getContext("2d"),
    canvasData = '';

function modify(){
    // Do some random stuff
    for(var i = 0; i < 10; i++){
        var ranR = Math.floor(Math.random() * 255),
            ranG = Math.floor(Math.random() * 255),
            ranB = Math.floor(Math.random() * 255);
        
        ctx.fillStyle = 'rgb(' + ranR + ',' + ranG + ',' + ranB + ')';
        ctx.fillRect(Math.random() * 100,Math.random() * 100,Math.random() * 10,Math.random() * 10);
    }
}

function clear(){
    ctx.fillStyle = "#fff";
    ctx.fillRect(0,0,100,100);  
}

function save(){
    // get the data
    canvasData = ctx.getImageData(0, 0, 100, 100);
}

function restore(){
    // restore the old canvas
    ctx.putImageData(canvasData, 0, 0);
}