Search code examples
javascripthtmlcanvasclip

Image context.restore();


Im starting to learn canvas and i just hit my first frustrating situation, im trying to make a clipping mask of a .jpg src in a triangle. Everything looks fine until i restore my context and try to add any other Path... my clipping mask appears to not exist anymore.

Here is my code :

    <script>
function init() {
    var canvas = document.getElementById('myCanvas');
    if(canvas.getContext) {

    var context = canvas.getContext('2d');
    var imageObj = new Image();
    imageObj.src = 'stephgopro2.jpg';

    // triangle coordonate
    context.save();
    context.beginPath;
    context.moveTo(100, 0);
    context.lineTo(0, 100);
    context.lineTo(200, 100);
    context.lineTo(100, 0);
    context.clip();

    imageObj.onload = function() {
        context.drawImage(imageObj, 0, 0, 300, 170);
    };

    context.restore();
    context.beginPath();
    context.fillStyle = '#333';
    context.rect(0, 0, 600, 200);
    context.fill();
    }
}
</script>

</head>
<body onload='init()'>
  <canvas id="myCanvas" width="600" height="200"></canvas>

</body>

Can you please help me with that? many thanks.


Solution

  • The image is loaded asynchronously so the context has already been restored before the image is drawn to the canvas. If you update the code as follows you'll get (what I think are) the results you expect:

    function init() {
        var canvas = document.getElementById('myCanvas');
            if(canvas.getContext) {
    
            var context = canvas.getContext('2d');
            var imageObj = new Image();
            imageObj.src = 'assets/1.jpg';
    
            // triangle coordonate
            context.save();
            context.beginPath();
            context.moveTo(100, 0);
            context.lineTo(0, 100);
            context.lineTo(200, 100);
            context.lineTo(100, 0);
            context.stroke();
            context.clip();
    
            imageObj.onload = function() {
                context.drawImage(imageObj, 0, 0, 300, 170);
    
                // Restore the context and continue drawing now the image has been drawn
                context.restore();
                context.beginPath();
                context.fillStyle = '#333';
                context.rect(0, 0, 600, 200);
                context.fill();
            };
        }
    }