1# <canvas> Development 2 3 4The **<canvas>** component provides a canvas for drawing customized graphics. For details, see [canvas](../reference/arkui-js/js-components-canvas-canvas.md). 5 6 7## Creating a <canvas> Component 8 9Create a **<canvas>** component in the .hml file under **pages/index**. 10 11 12``` 13<!-- xxx.hml --> 14<div class="container"> 15 <canvas></canvas> 16</div> 17``` 18 19 20```css 21/* xxx.css */ 22.container{ 23 flex-direction: column; 24 justify-content: center; 25 align-items: center; 26 background-color: #F1F3F5; 27} 28canvas{ 29 background-color: #00ff73; 30} 31``` 32 33 34 35> **NOTE** 36> 37> - The default background color of the **<canvas>** component is the same as that of the parent component. 38> 39> - The default width and height of **<canvas>** are 300 px and 150 px, respectively. 40 41 42## Adding Styles 43 44Set **width**, **height**, **background-color**, and **border** of the **<canvas>** component. 45 46 47```html 48<!-- xxx.hml --> 49<div class="container"> 50 <canvas></canvas> 51</div> 52``` 53 54 55```css 56/* xxx.css */ 57.container{ 58 flex-direction: column; 59 justify-content: center; 60 align-items: center; 61 background-color: #F1F3F5; 62} 63canvas{ 64 width: 500px; 65 height: 500px; 66 background-color: #fdfdfd; 67 border: 5px solid red; 68} 69``` 70 71 72 73 74## Adding Events 75 76Add the long press event to the **<canvas>** component. When the event is triggered, the value of **dataUrl** (image information returned by the **toDataURL** method) of the **<canvas>** component can be obtained and printed in the text area below. 77 78 79```html 80<!-- xxx.hml --> 81<div class="container"> 82 <canvas ref="canvas1" onlongpress="getUrl"></canvas> 83 <text>dataURL</text> 84 <text class="content">{{dataURL}}</text> 85</div> 86``` 87 88 89```css 90/* xxx.css */ 91.container{ 92 width:100%; 93 height:100%; 94 flex-direction: column; 95 justify-content: center; 96 align-items: center; 97 background-color: #F1F3F5; 98 } 99 canvas{ 100 width: 500px; 101 height: 500px; 102 background-color: #fdfdfd; 103 border: 5px solid red; 104 margin-bottom: 50px; 105} 106.content{ 107 border: 5px solid blue; 108 padding: 10px; 109 width: 90%; 110 height: 400px; 111 overflow: scroll; 112} 113``` 114 115 116```js 117// xxx.js 118import prompt from '@system.prompt'; 119export default { 120 data:{ 121 dataURL:null, 122 }, 123 onShow(){ 124 let el = this.$refs.canvas1; 125 let ctx = el.getContext("2d"); 126 ctx.strokeRect(100,100,300,300); 127 }, 128 getUrl(){ 129 let el = this.$refs.canvas1 130 let dataUrl = el.toDataURL() 131 this.dataURL = dataUrl; 132 prompt.showToast({duration:2000,message:"long press,get dataURL"}) 133 } 134} 135``` 136 137 138 139> **NOTE** 140> 141> The **<canvas>** component cannot be created in **onInit** or **onReady**. 142