HTML5 Game - Copying image from One Canvas to Another

Introduction

We can use another canvas as the source of a bitmap drawing operation.

Demo

ResultView the demo in separate window

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script type="text/javascript">
window.addEventListener('load', eventWindowLoaded, false);

function eventWindowLoaded() {/* w w w .j av a2  s  .  c o m*/
    canvasApp();
}

function canvasApp(){
        let theCanvas = document.getElementById("canvas");
        let context = theCanvas.getContext("2d");
        let theCanvas2 = document.getElementById("canvas2");
        let context2 = theCanvas2.getContext("2d");

    let tileSheet = new Image();
    tileSheet.addEventListener('load', eventSheetLoaded , false);
    tileSheet.src="http://java2s.com/style/download.png";
    function eventSheetLoaded() {
        startUp();
    }
    
    function startUp(){
        context.drawImage(tileSheet, 0, 0);
        context2.drawImage(theCanvas, 32, 0,32,32,0,0,32,32);
    }
}
</script>
</head>
<body>
<div>
<canvas id="canvas" width="256" height="256" style="position: absolute;
top: 50px; left: 50px;"> Your browser does not support HTML5 Canvas.</canvas>
<canvas id="canvas2" width="32" height="32" style="position: absolute;
top: 256px; left: 50px;">Your browser does not support HTML5 Canvas.</canvas>
</div>
</body>
</html>

Related Topic