简体   繁体   中英

Setting canvas width / height on creation

So I'm attempting to create a canvas object in a jQueryUI widget that has a width and height specified by the user. Then fill that canvas with a gradient.

Doing it this way doesn't work, the width of the fillrect is much too narrow

this.canvas = $("<canvas/>", { width: this.options.width, height: this.options.height }).appendTo(this.element);

However doing it this way works

this.canvas = $("<canvas width=\""+ this.options.width + "\" height=\""+ this.options.height + "\"/>").appendTo(this.element);

What is the difference between the two methods?

In the second case, the width and height of the canvas element will be added as an attribute, which is the correct way to set canvas width and height.

In the first case, canvas width and height will be set as a css style. Setting the canvas width and height using css won't set the actual width and height of canvas element, it'll only give a zoomed effect of original canvas (This size won't be considered to perform the internal calculations).

check the following SO Question for more info...

A quirk of $('<element/>', {properties}) is that height and width properties are applied as styles, not attributes.

You can probably do what you wanted with:

   $("<canvas/>").attr({ width: this.options.width, height: this.options.height }).appendTo(this.element);

JSFiddle: http://jsfiddle.net/TrueBlueAussie/LWB2Q/

In answer to your question actually asked, the first version applies properties as styles. This is limited to specific jQuery properties, for instance you cannot set {'background-color': 'green'} with it.

The second version sets height and width as attributes, which is what you needed, but the better way to do that is as shown in my example.

General advice: Concatenating strings for elements is always a bad idea (and best avoided).

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