jQuery equivalent of getting the context of a Canvas

前端 未结 4 1010
情歌与酒
情歌与酒 2020-11-30 00:18

I have the following working code:

ctx = document.getElementById(\"canvas\").getContext(\'2d\');

Is there any way to re-write it to use

4条回答
  •  心在旅途
    2020-11-30 01:03

    try{ 
       ctx = $('#canvas').get(0).getContext('2d');
    }catch(e){ 
        console.log('We have encountered an error: ' + e);
    }
    

    or...

    if( typeof $('#canvas') === 'undefined'){ 
        var canvas = '<\/canvas>';
        $('body').append(canvas);
    }
    setTimeout( function(){ ctx = $('#canvas').get(0).getContext('2d'); }, 500);
    

    Using setTimeout is an easy way to ensure you don't try calling the canvas element before it's fully created and registered to the DOM.

提交回复
热议问题