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

后端 未结 3 1961
鱼传尺愫
鱼传尺愫 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: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...

提交回复
热议问题