Is it possible to create an HTML canvas without a DOM element?

后端 未结 3 1960
鱼传尺愫
鱼传尺愫 2020-12-30 18:36

I\'d like to have an HTML canvas context that I can paint to and read off-screen (in this example, writing text and reading the shape that is created, but it\'s a general qu

相关标签:
3条回答
  • 2020-12-30 19:12

    Its old but what about saving one canvas with toDataURL and copying to the other with drawImage. you could also use save and restore to make a frame buffer

    function createCanvas(width, height) {
        var c = document.createElement('canvas');
        c.setAttribute('width', width);
        c.setAttribute('height', height);
        return c;
    }
    
    function canvasImg(canvas) {
        var ctx = canvas.getContext('2d');
        ctx.fillRect(0,0,canvas.width, canvas.height);
        var img = canvas.toDataURL('image/png');
    
        return img;
    }
    
    function placeImage(canvas, img) {
        var ctx = canvas.getContext('2d');
        ctx.drawImage(img, 0,0);
    }
    
    window.onload = function(){
        var canvas = createCanvas(400, 400);
        var hiddenCanvas = createCanvas(400,400);
        var i = canvasImg(hiddenCanvas);
        var img = new Image();
        img.src = i;
        placeImage(canvas, img);
        document.body.appendChild(canvas);
    }
    
    0 讨论(0)
  • 2020-12-30 19:15

    You can create a new canvas element with document.createElement:

    var canvas = document.createElement('canvas');
    

    and then get the context from it. Just make sure you set the width and height. You don't have to add the canvas to the tree in order to make it work:

    DEMO

    But you definitely have to create that node. You could create a function for that though:

    function createContext(width, height) {
        var canvas = document.createElement('canvas');
        canvas.width = width;
        canvas.height = height;
        return canvas.getContext("2d");
    }
    

    But that is where my competency ends... whether you can somehow transfer a context to another context or canvas, I don't know...

    0 讨论(0)
  • 2020-12-30 19:19

    There is apparently a new thing called OffscreenCanvas that was deliberately designed for this use case. An additional bonus is that it also works in Web Workers.

    You can read the specifications here: https://html.spec.whatwg.org/multipage/canvas.html#the-offscreencanvas-interface

    And see examples here: https://developer.mozilla.org/en-US/docs/Web/API/OffscreenCanvas

    Currently it is only fully supported by Chrome and is available behind flags in Firefox and Opera, but you can always check for the latest information on supported browsers here: https://caniuse.com/#feat=offscreencanvas

    ps.: Google also has a dedicated guide explaining it's use in Web Workers: https://developers.google.com/web/updates/2018/08/offscreen-canvas

    0 讨论(0)
提交回复
热议问题