Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to use Canvas to customize rounded rectangle in HTML5

Shulou Source: shulou.com Published: 2022-05-31 13:12:41 09月30日 Update

This article mainly explains "how to use Canvas to customize the rounded rectangle in HTML5". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to customize the rounded rectangle in HTML5 using Canvas".

HTML5 Canvas custom rounded rectangles and dashed lines (RoundedRectangle and Dash Line)

Realize the demonstration of adding self-defined functions to HTML Canvas 2d context drawing objects, how to draw dashed lines and control the size of dotted lines, and learn the skills of drawing rounded rectangles.

The native function provided in HTML5 Canvas drawing object does not realize the function of drawing rounded rectangle and dashed line, but these two functions can be added to object CanvasRenderingContext2D through Object.prototype of JavaScript language. The demonstration of the code is as follows:

The code for the component fishcomponent.js is as follows:

The code is as follows:

CanvasRenderingContext2D.prototype.roundRect =

Function (x, y, width, height, radius, fill, stroke) {

If (typeof stroke = = "undefined") {

Stroke = true

}

If (typeof radius = = "undefined") {

Radius = 5

}

This.beginPath ()

This.moveTo (x + radius, y)

This.lineTo (x + width-radius, y)

This.quadraticCurveTo (x + width, y, x + width, y + radius)

This.lineTo (x + width, y + height-radius)

This.quadraticCurveTo (x + width, y + height, x + width-radius, y + height)

This.lineTo (x + radius, y + height)

This.quadraticCurveTo (x, y + height, x, y + height-radius)

This.lineTo (x, y + radius)

This.quadraticCurveTo (x, y, x + radius, y)

This.closePath ()

If (stroke) {

This.stroke ()

}

If (fill) {

This.fill ()

}

}

CanvasRenderingContext2D.prototype.dashedLineTo = function (fromX, fromY, toX, toY, pattern) {

/ / default interval distance-> 5px

If (typeof pattern = = "undefined") {

Pattern = 5

}

/ / calculate the delta x and delta y

Var dx = (toX-fromX)

Var dy = (toY-fromY)

Var distance = Math.floor (Math.sqrt (dx*dx + dy*dy))

Var dashlineInteveral = (pattern

Tags: Rounded corners rectangles code functions dotted lines objects learning presentation content functions two size that is ideas situations skills effects articles more knowledge Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Microsoft Redmi Shulou Technology NVidia Shulou Tech Info