HTML5 Game - Canvas Canvas Images

Introduction

We can use the contents of one canvas as the source for the drawImage method on another.

Demo

ResultView the demo in separate window

<!DOCTYPE HTML>
<html>
    <head>
        <title>Example</title>
        <style>
            canvas {border: thin solid black}
            body > * {float:left;}
        </style>
    </head>
    <body>
        <video id="vid" hidden src="http://java2s.com/style/demo/your.webm" preload="auto" 
            width="360" height="240" autoplay></video>
        <canvas id="canvas" width="360" height="240">
            Your browser doesn't support the <code>canvas</code> element
        </canvas>
        <div>
            <button id="pressme">Press Me</button>
        </div>
        <canvas id="canvas2" width="360" height="240">
            Your browser doesn't support the <code>canvas</code> element
        </canvas>
        <script>
            let srcCanvasElement = document.getElementById("canvas");
            let ctx = srcCanvasElement.getContext("2d");
            let ctx2= document.getElementById("canvas2").getContext("2d");
            let imageElement = document.getElementById("vid");
            //from  w  w w  .  j a  va  2  s .co m
            document.getElementById("pressme").onclick = takeSnapshot;
            
            let width = 100;
            let height = 10;
            ctx.lineWidth = 5;
            ctx.strokeStyle = "red";
            ctx2.lineWidth = 30;
            ctx2.strokeStyle = "black;"
            
            setInterval(function() {
                ctx.drawImage(imageElement, 0, 0, 360, 240);
                ctx.strokeRect(180 - (width/2),120 - (height/2), width, height);
            }, 25);
            
            setInterval(function() {
                width = (width + 1) % 200;
                height = (height + 3) % 200;
            }, 100);
            
            function takeSnapshot() {
                ctx2.drawImage(srcCanvasElement, 0, 0, 360, 240);
                ctx2.strokeRect(0, 0, 360, 240);
            }
        </script>
    </body>
</html>

Related Topic