How to draw a rounded rectangle using HTML5Canvas
In this issue, the editor will bring you about how to use HTML5 Canvas to draw rounded rectangles. The article is rich in content and analyzes and narrates it from a professional point of view. I hope you can get something after reading this article.
The rounded rectangle is composed of four lines and four 1-stroke 4 arcs, which are disassembled as follows.
Because we are going to write a function instead of a fixed rounded rectangle, here are the parameters that the function needs. After the analysis, type the code directly.
JavaScript Code copies content to the clipboard
Rounded rectangle body {background: url (". / images/bg3.jpg") repeat;} # canvas {border: 1px solid # aaaaaa; display: block; margin: 50px auto;} your browser doesn't support canvas! Hurry up and change it! _ window.onload = function () {var canvas = document.getElementById ("canvas"); canvas.width = 800; canvas.height = 600; var context = canvas.getContext ("2d"); context.fillStyle = "# FFF"; context.fillRect (0Pol 0800600); drawRoundRect (context, 200,100,400,400,50); context.strokeStyle = "# 0078AA" Context.stroke ();} function drawRoundRect (cxt, x, y, width, height, radius) {cxt.beginPath (); cxt.arc (x + radius, y + radius, radius, Math.PI, Math.PI * 3 / 2); cxt.lineTo (width-radius + x, y) Cxt.arc (width-radius + x, radius + y, radius, Math.PI * 3 / 2, Math.PI * 2); cxt.lineTo (width + x, height + y-radius); cxt.arc (width-radius + x, height-radius + y, radius, 0, Math.PI * 1 / 2); cxt.lineTo (radius + x, height + y) Cxt.arc (radius + x, height-radius + y, radius, Math.PI * 1 / 2, Math.PI); cxt.closePath ();}
Running result:
It is recommended that you draw a rounded rectangle by yourself, which is helpful to master the path.
Let's use this function to do something else.
Draw 2048 game interface
Do not explain the code too much, we do their own research, it is recommended to try to write it yourself. Because what I use here is hard coding, so it is not very good, you can also try to optimize it.
JavaScript Code copies content to the clipboard
2048 Game interface body {background: url (". / images/bg3.jpg") repeat;} # canvas {border: 1px solid # aaaaaa; display: block; margin: 50px auto;} your browser doesn't support canvas! Hurry up and change it! _ window.onload = function () {var canvas = document.getElementById ("canvas"); canvas.width = 800; canvas.height = 600; var context = canvas.getContext ("2d"); context.fillStyle = "# FFF"; context.fillRect (0Pol 0800600); drawRoundRect (context, 200,100,400,400,5); context.fillStyle = "# AA7B41" Context.strokeStyle = "# 0078AA"; context.stroke (); context.fill (); for (var I = 1; I