Mitzi
Mitzi

Reputation: 47

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
    } ),

Upvotes: 0

Views: 189

Answers (1)

Austin Greco
Austin Greco

Reputation: 33554

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.

Upvotes: 3

Related Questions