简体   繁体   中英

Add an ID to a canvas using JavaScript

I'm trying to add an ID to a canvas using JavaScript however I'm trying to modify the following specific code. Please note, I am only assuming that this is where I would set the attribute. Cheers for any help.

THREE.CanvasRenderer = function ( parameters ) {

console.log( 'THREE.CanvasRenderer', THREE.REVISION );

parameters = parameters || {};

var _this = this,
    _renderData, _elements, _lights,
    _projector = new THREE.Projector(),

    _canvas = parameters.canvas !== undefined
             ? parameters.canvas
             : document.createElement( 'canvas' ),

    _canvasWidth = _canvas.width,
    _canvasHeight = _canvas.height,
    _canvasWidthHalf = Math.floor( _canvasWidth / 2 ),
    _canvasHeightHalf = Math.floor( _canvasHeight / 2 ),

    _viewportX = 0,
    _viewportY = 0,
    _viewportWidth = _canvasWidth,
    _viewportHeight = _canvasHeight,

    _pixelRatio = 1,

    _context = _canvas.getContext( '2d', {
        alpha: parameters.alpha === true
    } ),

You can just set the id property directly:

_canvas.id = 'whatever';

Edit

The above code should work, but it will need to be after the large variable initialization block you have:

// start var initialization
var _this = this,
    _renderData, _elements, _lights,
    _projector = new THREE.Projector(),

    _canvas = parameters.canvas !== undefined
             ? parameters.canvas
             : document.createElement( 'canvas' ),

    _canvasWidth = _canvas.width,
    _canvasHeight = _canvas.height,
    _canvasWidthHalf = Math.floor( _canvasWidth / 2 ),
    _canvasHeightHalf = Math.floor( _canvasHeight / 2 ),

    _viewportX = 0,
    _viewportY = 0,
    _viewportWidth = _canvasWidth,
    _viewportHeight = _canvasHeight,

    _pixelRatio = 1,

    _context = _canvas.getContext( '2d', {
        alpha: parameters.alpha === true
    } ),

    ... more code,

    theEnd = true;
// end var initialization

_canvas.id = 'whatever';

^ this whole thing is one big var initialization. At some point there it will end and there will probably be a semicolon. That's where you will add the id code.

I think you were getting an unexpected token error because you were trying to add some code between the commas in the var initialization.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM