Search code examples
htmlcanvashtml5-canvas

how to render offscreen canvas properly


I'm trying to create a basic example of offscreen rendering canvas but I'm error in js "cannot read property of context". actually my idea is to create a demo like I saw in https://yalantis.com/ I want to create my name initial. If there is any better idea to achieve this then please enlighten me. Thanks here is my basic attempt before the actual implementation :)

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Off Screen Canvas</title>
<script>
    function createOffscreenCanvas() {
        var offScreenCanvas= document.createElement('canvas');
        offScreenCanvas.width= '1360px';
        offScreenCanvas.height= '400px';
        var context= offScreenCanvas.getContext("2d");
        context.fillRect(10,10,200,200);
    }
    function copyToOnScreen(offScreenCanvas) {
        var onScreenContext=document.getElementById('onScreen').getContext('2d');
        var offScreenContext=offScreenCanvas.getContext('2d');
        var image=offScreenCanvas.getImageData(10,10,200,200);
        onScreenContext.putImageData(image,0,0);
    }
    function main() {
        copyToOnScreen(createOffscreenCanvas());
    }
</script>
<style>
    #onScreen {
        width:1360px;
        height: 400px;
    }
</style>
</head>  
 <body onload="main()">
 <canvas id="onScreen"></canvas>
 </body>
</html>

Solution

  • You could achieve this in the following way ...

    function createOffscreenCanvas() {
        var offScreenCanvas = document.createElement('canvas');
        offScreenCanvas.width = '1360';
        offScreenCanvas.height = '400';
        var context = offScreenCanvas.getContext("2d");
        context.fillStyle = 'orange'; //set fill color
        context.fillRect(10, 10, 200, 200);
        return offScreenCanvas; //return canvas element
    }
    
    function copyToOnScreen(offScreenCanvas) {
        var onScreenContext = document.getElementById('onScreen').getContext('2d');
        onScreenContext.drawImage(offScreenCanvas, 0, 0);
    }
    
    function main() {
        copyToOnScreen(createOffscreenCanvas());
    }
    canvas {
      border: 1px solid black;
    }
    <body onload="main()">
    <canvas id="onScreen" width="1360" height="400"></canvas>

    note : never set canvas's width and height using css. instead use the native width and height property of the canvas.