Safari Developer Library

Developer

HTMLCanvasElement Class Reference

Options
Deployment Target:

On This Page

HTMLCanvasElement

A canvas is an HTML element that defines a runtime drawing region within your web content. You can access the canvas as a JavaScript object and obtain a drawing context from it, in the form of a CanvasRenderingContext2D object. You draw on the canvas by using the JavaScript methods of the CanvasRenderingContext2D class.

  • width Property

    An integer containing the width of the canvas in CSS pixels.

    Declaration

    attribute long width

    Discussion

    Setting the width or height property, even without changing it, clears the canvas to transparent black and resets all context settings to their defaults, including the coordinate system and transformation matrix. If the width attribute is not specified in the <canvas> tag, the default width is 300 pixels.

  • height Property

    An integer containing the height of the canvas in CSS pixels.

    Declaration

    attribute long height

    Discussion

    Setting the width or height property, even without changing it, clears the canvas to transparent black and resets all context settings to their defaults, including the coordinate system and transformation matrix. If the height attribute is not specified in the <canvas> tag, the default height is 150 pixels.

  • Returns the drawing context for the canvas.

    Declaration

    DOMObject getContext (in DOMString contextId);

    Parameters

    contextId

    The identifier for the context. Currently, only the identifier "2d" is supported.

    Return Value

    The context object. Currently, always a CanvasRenderingContext2D object.

    Discussion

    Use the getContext method to obtain a drawing context for the canvas. All drawing on the canvas is done using the methods and properties of the context.

  • Returns a data URL containing an image of the canvas.

    Declaration

    DOMString toDataURL (in DOMStringtype in floatquality);

    Parameters

    type

    A string containing the MIME type of the data, such as "image/png". This parameter is optional. If omitted, the data URL is formatted as a .png file.

    quality

    A floating point number containing the quality of the JPEG image. This parameter is valid only if the type parameter is set to "image/jpeg". This parameter must be in the range of 0 to 1, inclusive. This parameter is optional. If omitted, the default quality of 1 is used (highest quality).

    Return Value

    Returns a data URL containing image data of a snapshot of the canvas. The image data is in .png format unless otherwise specified.

    Discussion

    Use this method to record an image of the canvas’ contents as .png or .jpg file. The method returns the image as a data URL. The image can be drawn back to the canvas later using the drawing context’s drawImage method.