Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to program HTML5 Canvas API

2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article introduces you how to program HTML5 Canvas API, the content is very detailed, interested friends can refer to, hope to be helpful to you.

The code is as follows:

Try

{

Document.createElement ("Canvas") .getContext ("2D")

Document.getElementById ("support") [xss_clean] = "OK"

}

Catch (e)

{

Document.getElementById ("support") [xss_clean] = e.message

}

Join Canvas

The code is as follows:

/ / get the Canvas element and its drawing context var canvas = document.getElementById ("diagonal")

Var context = canvas.getContext ("2d")

/ / create a path with absolute coordinates

Context.beginPath ()

Context.moveTo (70,140)

Context.lineTo (140,70)

/ / draw this line to Canvas

Context.stroke ()

Transform

You can achieve the same effect as above by transforming (zoom, pan, rotate), and so on.

Draw diagonals by transformation

The code is as follows:

/ / get the Canvas element and its drawing context

Var canvas = document.getElementById ("diagonal")

Var context = canvas.getContext ("2d")

/ / Save the current drawing state

Context.save ()

/ / move the drawing context to the lower right

Context.translate (70,140)

/ / draw the same line segment as before, starting from the origin

Context.beginPath ()

Context.moveTo (0,0)

Context.lineTo (70,-70)

Context.stroke ()

Context.restore ()

Path

The path in HTML5 Canvas API represents any shape you want to present.

BeginPath (): no matter what graph you start drawing, the first thing you need to call is beginPath. This simple function takes no arguments and is used to inform canvas that a new graph is about to be drawn.

MoveTo (xrecoery y): do not draw, move the current position to the new target coordinates (xrecoery y).

LineTo (xrecoery y): not only moves the current position to the new target coordinates (xrecoery y), but also draws a straight line between the two coordinates.

ClosePath (): this function behaves much like lineTo except that closePath automatically takes the starting coordinates of the path as the target coordinates. It also informs canvas that the current drawing has been closed or has formed a completely enclosed area, which is useful for future fills and strokes.

Draw the crown of a pine tree

The code is as follows:

Function createCanopyPath (context) {

/ / Draw the tree canopy

Context.beginPath ()

Context.moveTo (- 25,-50)

Context.lineTo (- 10,-80)

Context.lineTo (- 20,-80)

Context.lineTo (- 5,-110)

Context.lineTo (- 15,-110)

/ / the vertex of the tree

Context.lineTo (0,140)

Context.lineTo (15,-110)

Context.lineTo (5,-110)

Context.lineTo (20,-80)

Context.lineTo (10-80)

Context.lineTo (25,-50)

/ / connection start point, closed path

Context.closePath ()

}

Function drawTrails () {

Var canvas = document.getElementById ('diagonal')

Var context = canvas.getContext ('2d')

Context.save ()

Context.translate (130,250)

/ / create a path to represent the tree crown

CreateCanopyPath (context)

/ / draw the current path

Context.stroke ()

Context.restore ()

}

Window.addEventListener ("load", drawTrails, true)

Stroke styl

Through the stroke mode, you can make the crown look more realistic.

The code is as follows:

/ / widen the line

Context.lineWidth = 4

/ / the joint of a smooth path

Context.lineJoin = 'round'

/ / Color

Context.strokeStyle ='# 663300'

/ / draw the current path

Context.stroke ()

Fill pattern

Context.fillStyle = "# 339900"; context.fill ()

Draw a rectangle

We added trunks to the tree

Context.fillStyle ='# 663300; context.fillRect (- 5,-50, 10, 50)

Draw a curve

The code is as follows:

Context.save ()

Context.translate (- 10350)

Context.beginPath ()

/ / the first curve bends to the upper right

Context.moveTo (0,0)

Context.quadraticCurveTo (170,50,260,190)

/ / Bend to the lower right

Context.quadraticCurveTo (310,-250,410,-250)

/ / Draw the path in a wide brown stroke

Context.strokeStyle ='# 663300'

Context.lineWidth = 20

Context.stroke ()

/ / Restore the previous canvas state

Context.restore ()

Insert a picture in Canvas

You must wait until the picture is fully loaded before you can manipulate it. Browsers usually load pictures asynchronously when page scripts are executed, and if you try to render them to canvas before they are fully loaded, canvas will not display any pictures, so be careful to make sure the pictures are loaded before rendering.

The code is as follows:

/ / load pictures

Var bark = new Image ()

Bark.src = "bark.jpg"

/ / after the picture is loaded, call the drawing function

Bark.onload = function () {

DrawTrails ()

}

Show picture:

/ / fill with background pattern as the background context.drawImage of the tree trunk (bark,-5,-50, 10, 50)

Gradual change

Using gradients requires three steps:

(1) create a gradient object

(2) set the color for the gradient object and indicate the transition mode

(3) set gradients for fill or stroke styles on context

The code is as follows:

/ / create a third-order horizontal gradient used as a trunk texture

Var trunkGradient = context.createLinearGradient (- 5,-50, 5,-50)

/ / the left edge of the trunk is average brown.

TrunkGradient.addColorStop (0,'# 663300')

/ / the position of the middle left of the trunk needs to be discussed.

TrunkGradient.addColorStop (0.4,'# 996600')

/ / the right edge is darker.

TrunkGradient.addColorStop (1,'# 552200')

/ / fill the trunk with a gradient

Context.fillStyle = trunkGradient

Context.fillRect (- 5,-50, 10, 50)

/ / create a vertical gradient to use the projection of the crown on the trunk

Var canopyShadow = context.createLinearGradient (0,-50,0,0)

/ / the starting point of the projection gradient is black with 50% transparency

CanopyShadow.addColorStop (0, 'rgba (0,0,0,0.5)')

/ / the direction is vertically downward, and the gradient changes rapidly to completely transparent in a very short distance, beyond this length.

/ / there is no projection on the tree trunk

CanopyShadow.addColorStop (0.2, 'rgba (0,0,0,0.0)')

/ / fill the projection gradient on the tree trunk

Context.fillStyle = canopyShadow

Context.fillRect (- 5,-50, 10, 50)

Background map

The code is as follows:

/ / load pictures

Var gravel = new Image ()

Gravel.src = "gravel.jpg"

Gravel.onload = function () {

DrawTrails ()

}

/ / replace thick brown lines with background images

Context.strokeStyle = context.createPattern (gravel, 'repeat')

Context.lineWidth = 20

Context.stroke ()

The second parameter of context.createPattern is the repeatability tag, and you can select the appropriate value in Table 2-1.

Meaning of tiling method repeat (default) the picture will be tiled in both directions repeat-x horizontally tiled repeat-y vertically tiled no-repeat picture is displayed only once, not tiled

Scalin

The scaling function context.scale (XPerry y): XPerry y represents the values in the two dimensions of XMagi y, respectively. When each parameter displays an image in canvas, it is passed the amount of image to be enlarged (or reduced) on the axis in this direction. If the x value is 2, it means that all elements in the drawn image will become twice as wide, if the y value is 0. 5, the drawn image will become half as high as before.

The code is as follows:

/ / draw the first tree at Xtrees 130, Ytrees 250

Context.save ()

Context.translate (130,250)

DrawTree (context)

Context.restore ()

/ / draw the second tree at Xtrees 260, Ytrees 500

Context.save ()

Context.translate (260,500)

/ / double the height and width of the second tree

Context.scale (2,2)

DrawTree (context)

Context.restore ()

Rotation

Rotate the image

The code is as follows:

Context.save ()

/ / rotation angle parameter is measured in radians

Context.rotate (1.57)

Context.drawImage (myImage, 0,0,100,100)

Context.restore ()

A method of using transformation

The code is as follows:

/ / Save current status

Context.save ()

/ / the X value increases with the increase of Y value, with the help of stretch transformation

/ / you can create a sloping tree to use as a shadow

/ / after the transformation is applied, all coordinates are multiplied by the matrix

Context.transform (1,0)

-0.5, 1

, 0)

/ / in the Y axis, change the shadow height to 60% of its original height.

Context.scale (1,0.6)

/ / fill the trunk with black with 20% transparency

Context.fillStyle = 'rgba (0,0,0,0.2)'

Context.fillRect (- 5,-50, 10, 50)

/ / redraw the tree using the existing shadow effect

CreateCanopyPath (context)

Context.fill ()

/ / restore the previous canvas status

Context.restore ()

Text

Context.fillText (text,x,y,maxwidth): text text content, XMagi y specifies the text location, and maxwidth is an optional parameter that restricts the text location.

Context.strokeText (text,x,y,maxwidth): text text content, XMagi y specifies the text location, and maxwidth is an optional parameter that restricts the text location.

The code is as follows:

/ / draw text on canvas

Context.save ()

/ / Font size is 60 and font is Impact

Context.font = "60px impact"

/ / fill color

Context.fillStyle ='# 996600'

/ / Center

Context.textAlign = 'center'

/ / draw text

Context.fillText ('Happy Trails traders, 200,60,400)

Context.restore ()

shadow

Shadows can be controlled through several global context properties

Attribute values Note shadowColor Color values in any CSS can use transparency (alpha) shadowOffsetX pixel values are positive, move shadows to the right; negative, move shadows shadowOffsetY pixel values to the left are positive, move shadows downwards; negative, move shadows upward the greater the shadowBlur Gaussian blur value, the more blurred the shadow edge

The code is as follows:

/ / Color black, 20% transparency

Context.shadowColor = 'rgba (0,0,0,0.2)'

/ / move 15px to the right and 10px to the left

Context.shadowOffsetX = 15

Context.shadowOffsetY =-10

/ / slightly blurred shadow

Context.shadowBlur = 2

Pixel data

Context.getImageData (sx, sy, sw, sh): sx,xy determines a point, sw: width, sh: height.

This function returns three properties: how many pixels are there in width per row? how many pixels are in height per column?

Data is a stack of arrays containing the RGBA values (red, green, blue, and transparency) of each pixel obtained from canvas.

Context.putImageData (imagedata,dx,dy): allows developers to pass in a set of image data. Dx,dy is used to specify the offset. If used, this function jumps to the specified canvas location to update.

Displays the incoming pixel data.

Canvas.toDataUrl: the data currently rendered on the canvas can be obtained programmatically, saved in text format, and parsed into images by browsers.

On how to program HTML5 Canvas API to share here, I hope that the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report