js-components-canvas-image.md 1.5 KB
Newer Older
E
ester.zhou 已提交
1
# Image
Z
zengyawen 已提交
2

E
ester.zhou 已提交
3 4 5
>  **NOTE**
>
>  This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version.
Z
zengyawen 已提交
6

E
ester.zhou 已提交
7
The **Image** object is an image on the canvas.
Z
zengyawen 已提交
8 9


E
ester.zhou 已提交
10
## Attributes
Z
zengyawen 已提交
11

E
ester.zhou 已提交
12 13 14 15 16 17 18 19 20 21 22 23
| Name     | Type            | Default Value | Mandatory  | Description               |
| ------- | -------------- | ---- | ---- | ----------------- |
| src     | string         | -    | Yes   | Image resource path.         |
| width   | <length> | 0px  | No   | Image width.           |
| height  | <length> | 0px  | No   | Image height.           |
| onload  | Function       | -    | No   | Function called when an image is successfully loaded. This function has no parameter.|
| onerror | Function       | -    | No   | Function called when an image fails to be loaded. This function has no parameter.|


## Example

```html
Z
zengyawen 已提交
24 25 26 27
<!-- xxx.hml -->
<div>
  <canvas ref="canvas" style="width: 500px; height: 500px; "></canvas>
</div>
Z
zengyawen 已提交
28 29
```

E
ester.zhou 已提交
30 31
```js
// xxx.js
Z
zengyawen 已提交
32
export default {
E
ester.zhou 已提交
33 34 35 36 37 38 39 40 41 42 43 44 45 46
    onShow() {
        const el = this.$refs.canvas;
        var ctx = el.getContext('2d');
        var img = new Image();
        // It is recommended that the image be stored in the common directory.
        img.src = 'common/images/example.jpg';
        img.onload = function () {
            console.log('Image load success');
            ctx.drawImage(img, 0, 0, 360, 250);
        };
        img.onerror = function () {
            console.log('Image load fail');
        };
    }
Z
zengyawen 已提交
47 48 49
}
```

Z
zengyawen 已提交
50

E
ester.zhou 已提交
51
![1-9](figures/1-9.png)