Home >Web Front-end >H5 Tutorial >Detailed explanation of the sample code for drawing a rectangle in HTML5 canvas basic drawing
3856173a0eceb679792f65a38e1fcb00c2caaf3fc160dd2513ce82f021917f8b is a new tag in HTML5, which is used to draw graphics. This article is mainly for everyone This article introduces the basic drawing method of drawing a rectangle in HTML5 canvas in detail. Interested friends can refer to it
5ba626b379994d53f7acf72a64f9b697c2caaf3fc160dd2513ce82f021917f8bIt’s just a In addition to attributes such as id, class, and style, the container for drawing graphics also has height and width attributes. There are three main steps for drawing on the 5ba626b379994d53f7acf72a64f9b697> element:
1. Get theDOM object corresponding to the 5ba626b379994d53f7acf72a64f9b697 element, which is a Canvas object; 2. Call the getContext() method of the Canvas object to get a CanvasRenderingContext2D object;
3. Call the CanvasRenderingContext2D object for drawing.
Draw rectangles rect(), fillRect() and strokeRect()
•context.rect(x, y, width, height): only define the path of the rectangle ; •context.fillRect( x , y , width , height ): directly draw a filled rectangle;
•context.strokeRect( x , y , width , height ): directly draw a rectangular border;
JavaScript Code复制内容到剪贴板 <script type="text/javascript"> var canvas = document.getElementById("canvas"); var context = canvas.getContext("2d"); //使用rect方法 context.rect(10,10,190,190); context.lineWidth = 2; context.fillStyle = "#3EE4CB"; context.strokeStyle = "#F5270B"; context.fill(); context.stroke(); //使用fillRect方法 context.fillStyle = "#1424DE"; context.fillRect(210,10,190,190); //使用strokeRect方法 context.strokeStyle = "#F5270B"; context.strokeRect(410,10,190,190); //同时使用strokeRect方法和fillRect方法 context.fillStyle = "#1424DE"; context.strokeStyle = "#F5270B"; context.strokeRect(610,10,190,190); context.fillRect(610,10,190,190); </script>
clearRect(x,y,width,height). The received parameters are: clear the starting position of the rectangle and the width and length of the rectangle.
In the above code, add at the end of drawing the graphics:
context.clearRect(100,60,600,100);
The following effect can be obtained:
The above is the detailed content of Detailed explanation of the sample code for drawing a rectangle in HTML5 canvas basic drawing. For more information, please follow other related articles on the PHP Chinese website!