Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a canvas element and setting its width and height attributes using jQuery

I was just trying to do the following in jQuery:

var newCanvas = $('<canvas/>',{'width':100,'height':200,'class':'radHuh'}); $(body).append(newCanvas); 

This is working (kind of) and generates the following markup:

<canvas style="width:100px; height:200px;" class="radHuh"></canvas> 

As most of you might know canvas elements don't really like CSS dimensions but expect a width and height attribute, so this object creation failed for me.

I do know I could just do:

var newCanvas = $('<canvas/>',{'class':'radHuh'}).attr({'width':100,'height':200}); 

instead, but I was just wondering nonetheless if there is any way of telling jQuery that width and height should be treated as attributes when creating the element via $('element',{attributes}) and not as CSS?

like image 729
m90 Avatar asked May 03 '12 14:05

m90


People also ask

How can get canvas width and height in jQuery?

You can get the width and height of a canvas element simply by accessing those properties of the element. For example: var canvas = document. getElementById('mycanvas'); var width = canvas.

How do I change the width and height of a canvas in HTML?

The height attribute specifies the height of the <canvas> element, in pixels. Tip: Use the width attribute to specify the width of the <canvas> element, in pixels. Tip: Each time the height or width of a canvas is re-set, the canvas content will be cleared (see example at bottom of page).

What is the default height and width of the canvas element?

By default, the browser creates canvas elements with a width of 300 pixels and a height of 150 pixels. You can change the size of a canvas element by specifying the width and height attributes.

Does canvas use jQuery?

The direct answer is no because jQuery is based on DOM querying and manipulation. Canvas elements are drawn using the Canvas API with JavaScript. If you're looking for a good canvas library, you might try out KineticJS.


1 Answers

jQuery try to match each attribute name with a jQuery function name. Matched functions are called.

width and height are jQuery functions, so your original code is equivalent to this:

  var newCanvas =      $('<canvas/>',{'class':'radHuh'})     .width(100)     .height(100); 

width(value) and height(value) functions set CSS width and height of an element.


Relevant jQuery source code line (https://github.com/jquery/jquery/blob/master/src/attributes.js#L308)

if ( pass && name in jQuery.attrFn ) { 

attrFn object definition (https://github.com/jquery/jquery/blob/master/src/attributes.js#L288):

attrFn: {     val: true,     css: true,     html: true,     text: true,     data: true,     width: true,     height: true,     offset: true }, 
like image 71
Juan Mellado Avatar answered Oct 06 '22 03:10

Juan Mellado