JSFiddle - React, Tailwind, and code Playground

by vijayweb

HTML

<canvas id="canvas1" width="400" height="400" style="border: 1px solid black"></canvas>

JavaScript

var can = document.getElementById('canvas1');
var ctx = can.getContext('2d');

var inMem = document.createElement('canvas');
inMem.width = can.width;
inMem.height = can.height;
var inMeMctx = inMem.getContext('2d');

var firstTime = true;

can.addEventListener('mouseover', function() {
    // The first time this happens, save the canvas bitmap to an in-memory canvas
    if (firstTime === true) {
        inMeMctx.drawImage(can, 0, 0);
        firstTime = false;
    }

    // Draw some stuff
    ctx.beginPath();
    ctx.moveTo(10, 10);
    ctx.lineTo(40, 40);
    ctx.moveTo(40, 10);
    ctx.lineTo(10, 40);
    ctx.stroke();
    ctx.closePath();
}, false);

can.addEventListener('mouseout', function() {
    ctx.clearRect(0,0,can.width, can.height);
    // draw back our saved bitmap
    ctx.drawImage(inMem, 0, 0);
    // reset firstTime
    firstTime = true;
}, false);







// Lets have some default stuff on the canvas
ctx.save();
ctx.fillStyle = 'red';
ctx.fillRect(50,50,50,50);
ctx.fillText('This is default stuff', 100, 100);
ctx.restore();