Off screen canvas

Time:2021-11-5

Off screen canvas can solve the performance problem of canvas

Operation steps:

1. Create off screen canvas;
2. Set the width and height of off screen canvas;
3. Draw in off screen canvas;
4. Draw all or part of the off screen canvas onto the canvas being displayed

domo:

var canvas = document.getElementById('canvas'),
    context = canvas.getContext('2d'),

    offscreenCanvas = document.createElement('canvas'),
    offscreenContext = offscreenCanvas.getContext('2d');

    offscreenCanvas.width = canvas.width;
    offscreenCanvas.height = canvas.height;

var image = new Image();
image.src = 'balabal.jpg';

image.onload = function(){
    context.drawImage(image, 0, 0, canvas.width, canvas.height);
    offscreenContext.drawImage(image, 0, 0, canvas.width, canvas.height);
}

function oncangeDraw(){
    var w = canvas.width,
        h = canvas.height,
        sw = w * scale,
        sh = h * scale;

    //Draw the off screen canvas directly onto the real canvas
    context.drawImage(offscreenCanvas, 0, 0, 
    offscreenCanvas.width, offscreenCanvas.height,
    -sw/2 + w/2, -sh/2 + h/2, sw, sh);
}