Home >Web Front-end >H5 Tutorial >Programming HTML5 Canvas API _html5 tutorial skills

Programming HTML5 Canvas API _html5 tutorial skills

WBOY
WBOYOriginal
2016-05-16 15:49:431247browse


Copy code
The code is as follows:



Join Canvas


Copy code
The code is as follows:

//Get the Canvas element and its drawing context var canvas = document.getElementById("diagonal");
var context = canvas.getContext("2d");
//Use absolute coordinates to create a path
context.beginPath();
context.moveTo(70, 140);
context.lineTo(140, 70);
//Draw this line to Canvas
context.stroke();

Transform

The same effect as above can be achieved through transformation (zooming, translation, rotation), etc.

Draw diagonal lines using transformation


Copy code
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);
//Using the origin as the starting point, draw the same line segment as before
context.beginPath();
context .moveTo(0, 0);
context.lineTo(70, -70);
context.stroke();

context.restore();

Path

Paths in the HTML5 Canvas API represent any shape you wish to render.

beginPath(): No matter what kind of graphics you start drawing, the first thing that needs to be called is beginPath. This simple function takes no parameters and is used to notify the canvas that it is about to start drawing a new graphic.

moveTo(x,y): Move the current position to the new target coordinates (x,y) without drawing.

lineTo(x,y): Not only moves the current position to the new target coordinates (x,y), but also draws a straight line between the two coordinates.

closePath(): This function behaves very much like lineTo. The only difference is that closePath will automatically use the starting coordinates of the path as the target coordinates. It also notifies the canvas that the currently drawn shape is closed or forms a completely enclosed area, which is very useful for future fills and strokes.

Draw a pine tree canopy


Copy code
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 vertices 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);
// Connect the starting 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 representing the canopy
createCanopyPath(context);

// Draw the current path
context.stroke();
context.restore();
}

window.addEventListener("load", drawTrails, true);

Stroke style

Use the stroke mode to make the tree crown look more realistic.


Copy code
The code is as follows:

//Widen the line
context .lineWidth = 4;
//The joint point of the smooth path
context.lineJoin = 'round';
//Color
context.strokeStyle = '#663300';
//Drawing Current path
context.stroke();

Fill style

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

Draw a rectangle

We add a trunk to the tree

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

Draw a curve


Copy code
The code is as follows:

context.save();
context.translate(-10, 350);
context.beginPath();

// The first curve curves upward to the right
context.moveTo(0, 0);
context.quadraticCurveTo(170, -50, 260, -190);

//Curve 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 pictures in Canvas

You must wait until the image has fully loaded before you can operate on it. Browsers usually load images asynchronously when the page script is executed. If you try to render the image to the canvas before it is fully loaded, the canvas will not display any image. Therefore, special attention should be paid to ensuring that the image is Loaded.


Copy code
The code is as follows:

// Load image
var bark = new Image();
bark.src = "bark.jpg";

// After the image is loaded, call the drawing function
bark.onload = function () {
drawTrails();
}

Show picture:

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

Gradient

Using gradients requires three steps:

(1) Create gradient object

(2) Set the color for the gradient object and specify the transition method

(3) Set gradient for fill style or stroke style on context


Copy the code
The code is as follows:

// Create a three-dimensional tree trunk texture Order horizontal gradient
var trunkGradient = context.createLinearGradient(-5, -50, 5, -50);

//The left edge of the trunk is generally brown
trunkGradient.addColorStop(0, '#663300');

// The color of the middle left part of the trunk needs to be discussed
trunkGradient.addColorStop(0.4, '#996600');

//The color on the right edge should be darker
trunkGradient.addColorStop(1, '#552200');

// Fill the trunk with gradient
context.fillStyle = trunkGradient;
context.fillRect(-5, -50, 10, 50);
// Create a vertical gradient to fill the trunk with the canopy Shadow on the tree trunk
var canopyShadow = context.createLinearGradient(0, -50, 0, 0);
// The starting point of the projection gradient is black with a transparency of 50%
canopyShadow.addColorStop(0, ' rgba(0, 0, 0, 0.5)');
// The direction is vertically downward. The gradient quickly changes to completely transparent within a short distance. There is no tree trunk
// beyond this length. Projection
canopyShadow.addColorStop(0.2, 'rgba(0, 0, 0, 0.0)');

// Fill the tree trunk with the projection gradient
context.fillStyle = canopyShadow;
context.fillRect(-5, -50, 10, 50);

Background image


Copy code
The code is as follows:

// Load image
var gravel = new Image();
gravel.src = "gravel.jpg";
gravel.onload = function () {
drawTrails();
}

//Replace the thick brown line with a background image
context.strokeStyle = context.createPattern(gravel, 'repeat');
context.lineWidth = 20;
context.stroke();

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

平铺方式   意义
repeat (默认值)图片会在两个方向平铺
repeat-x 横向平铺
repeat-y 纵向平铺
no-repeat 图片只显示一次,不平铺

Zoom

Scaling function context.scale(x,y): x and y represent the values ​​in the x and y dimensions respectively. When each parameter displays an image on the canvas, it is passed the amount by which the image should be enlarged (or reduced) on the axis of the 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.


Copy code
The code is as follows:

// At X=130, Y= Draw the first tree at 250
context.save();
context.translate(130, 250);
drawTree(context);
context.restore();

// Draw the second tree at X=260, Y=500
context.save();
context.translate(260, 500);

//Enlarge the height and width of the second tree to 2 times the original value
context.scale(2, 2);
drawTree(context);
context.restore();

Rotate

Rotate image


Copy code
The code is as follows:

context.save();
//The rotation angle parameter is in radians
context.rotate(1.57);
context.drawImage(myImage, 0, 0, 100, 100);

context.restore();

A way to use transformation


Copy code
The code is as follows:

// Save the current state
context .save();

// The X value increases as the Y value increases. With the help of the stretch transformation,
// you can create a tilted tree used as a shadow
// After applying the transformation, all coordinates are Multiply with matrix
context.transform(1, 0,
-0.5, 1,
, 0);

// In the Y-axis direction, change the shadow height to 60% of the original value
context.scale(1, 0.6);

// Fill the trunk with black with a transparency of 20%
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 state
context.restore();

Text

context.fillText(text,x,y,maxwidth): text text content, x,y specifies the text position, maxwidth is an optional parameter, limiting the text position.
context.strokeText(text,x,y,maxwidth): text text content, x,y specifies the text position, maxwidth is an optional parameter, limiting the text position.


Copy code
The code is as follows:

// Draw text on canvas
context.save();

//The font size is 60 and the font is Impact
context.font = "60px impact";

//Fill color
context.fillStyle = '#996600';
//Center
context.textAlign = 'center';

//Draw text
context.fillText('Happy Trails!', 200, 60, 400);
context.restore();

Shadow

Shadows can be controlled through several global context properties

属性  值  备注
shadowColor  任何CSS中的颜色值 可以使用透明度(alpha)
shadowOffsetX 像素值  值为正数,向右移动阴影;为负数,向左移动阴影
shadowOffsetY 像素值 值为正数,向下移动阴影;为负数,向上移动阴影
shadowBlur 高斯模糊值 值越大,阴影边缘越模糊


Copy code
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 determine a point, sw: width, sh: height.

This function returns three attributes: width how many pixels in each row height how many pixels in each column

Data's group of RGBA values ​​(value red, green, blue and transparency) with each pixel obtained from Canvas.

context.putImageData(imagedata,dx,dy): allows developers to pass in a set of image data. dx and dy are used to specify the offset. If used, the function will jump to the specified canvas position. Update

Display the incoming pixel data.

canvas.toDataUrl: The data currently presented on the canvas can be obtained programmatically. The obtained data is saved in text format and the browser can parse it into an image.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn