Introduction to Canvas Foundation (4)
【 Today’s Lesson 】
- How do I use images in Canvas
- How do I use shadows in canvas
- Draw text information on canvas
【 Finish your goal today 】
After so many days of sharing, I think I have mastered some of the basics of Canvas. Today, I will implement a line chart of the basic class. Advanced version: I will try to dynamically create this line chart driven by data.
1. Use pictures
To use an Image in canvas, you need to use the Image constructor provided natively in JavaScript to generate an Image object, because the Image method provided by Canvas takes two arguments. The first argument is an image object or another canvas object. The first argument is the same as background-repeat in CSS: repeat, repeat-x, repeat-y, no-repeat. Create an image using the createPattern method.
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
<title>Introduction to Canvas Foundation (4)</title>
<style>
#canvasBox{
border: 1px solid #ccc;
display: block;
margin: 100px auto;
}
</style>
</head>
<body>
<canvas width="500" height="500" id="canvasBox">Your browser does not support canvas tag rendering. Please open it in Google Chrome or Firefox</canvas>
<script type="text/javascript">
// Get the Canvas box
let canvas = document.getElementById("canvasBox");
// Get the canvas context object
let ctx = canvas.getContext("2d");
// Check whether the current browser supports it
if ( ctx ) {
// Generate a picture object
let img = new Image();
// Load the image path
img.src = "./1.jpg";
// Listen image loading successfully
img.onload = () = > {
// Create a Canvas image object
let ctxImg = ctx.createPattern(img, 'repeat');
// Assign to the style
ctx.fillStyle = ctxImg;
// Create rectangle
ctx.fillRect(10.10.300.300); }}else {
console.log("Your current browser does not support Canvas");
}
</script>
</body>
</html>
Copy the code
[Effect drawing]
You can see that when the second parameter of createPattern is repeat, the x and y axes will be tiled. Modify the second parameter, will have a different tiling effect.
“Repeat – x”
【 repeat – y 】
No – repeat 】 【
2. Use shadows
You can see shadow effects on many websites, text shadow, box shadow. We use a lot of them. Shadow drawing is also supported on canvas.
Canvas provides four properties to set the shadow effect. ShadowOffsetX sets the position of the shadow extended on the X axis, shadowOffsetY sets the position of the shadow extended on the Y axis, and shadowBlur sets the blur degree of the shadow. The default value of the two properties is 0. ShadowColor is the color of the shadow, which is consistent with the CSS color. The default is transparent black.
Let’s use a small example to get a feel for the shadow effect of canvas
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
<title>Introduction to Canvas Foundation (4)</title>
<style>
#canvasBox{
border: 1px solid #ccc;
display: block;
margin: 100px auto;
}
</style>
</head>
<body>
<canvas width="500" height="500" id="canvasBox">Your browser does not support canvas tag rendering. Please open it in Google Chrome or Firefox</canvas>
<script type="text/javascript">
// Get the Canvas box
let canvas = document.getElementById("canvasBox");
// Get the canvas context object
let ctx = canvas.getContext("2d");
// Check whether the current browser supports it
if ( ctx ) {
// Set the shadow extension position
ctx.shadowOffsetX = 10;
ctx.shadowOffsetY = 10;
// Set the blur level
ctx.shadowBlur = 10;
// Set the shadow color
ctx.shadowColor = "Rgba (255,0,255, 0.5)";
// Set the box color
ctx.fillStyle = "#f0f";
// Draw a rectangle
ctx.fillRect(100.100.100.100);
} else {
console.log("Your current browser does not support Canvas");
}
</script>
</body>
</html>
Copy the code
[Effect drawing]
It’s easy to use a shadow on a canvas, just four properties to show it. Just set the positive shadow. When setting the position, the value can be negative. Add the shadow to the top and right of the box.
// Set the shadow extension position
ctx.shadowOffsetX = -10;
ctx.shadowOffsetY = -10;
Copy the code
[Effect drawing]
If you are careful, you may find a problem that canvas does not provide a property that has shadows on both sides of the box. How can you make the box have shadows on all sides?
Since canvas does not have five parameters like the SHADOW provided by CSS styles in HTML, set the spread scope. Then you can only see a simple shadow effect around
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
<title>Introduction to Canvas Foundation (4)</title>
<style>
#canvasBox{
border: 1px solid #ccc;
display: block;
margin: 100px auto;
}
</style>
</head>
<body>
<canvas width="500" height="500" id="canvasBox">Your browser does not support canvas tag rendering. Please open it in Google Chrome or Firefox</canvas>
<script type="text/javascript">
// Get the Canvas box
let canvas = document.getElementById("canvasBox");
// Get the canvas context object
let ctx = canvas.getContext("2d");
// Check whether the current browser supports it
if ( ctx ) {
// Set the shadow extension position
ctx.shadowOffsetX = 0;
ctx.shadowOffsetY = 0;
// Set the blur level
ctx.shadowBlur = 20;
// Set the shadow color
ctx.shadowColor = "Rgba (255,0,255, 1)";
// Set the box color
ctx.fillStyle = "#f0f";
// Draw a rectangle
ctx.fillRect(100.100.100.100);
} else {
console.log("Your current browser does not support Canvas");
}
</script>
</body>
</html>
Copy the code
[Effect drawing]
3. Draw text
We learned how to draw a line, how to draw a circle, draw a curved shape, set styles, use pictures, use shadows. It has not yet involved the development of text, canvas common usage scenarios, chart plug-ins, shared posters, and other image synthesis algorithms and small games. Words are definitely essential.
Canvas provides two methods for drawing text. FillText (text, x, y[, maxWidth]), strokeText(text, x, y[, maxWidth]), both methods have the same parameters. The first parameter is the text information to draw, x,y determine the position of the text to start drawing. The last parameter, optional, is the maximum width of the text to draw. If the text exceeds. Will scale the text.
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
<title>Introduction to Canvas Foundation (4)</title>
<style>
#canvasBox{
border: 1px solid #ccc;
display: block;
margin: 100px auto;
}
</style>
</head>
<body>
<canvas width="500" height="500" id="canvasBox">Your browser does not support canvas tag rendering. Please open it in Google Chrome or Firefox</canvas>
<script type="text/javascript">
// Get the Canvas box
let canvas = document.getElementById("canvasBox");
// Get the canvas context object
let ctx = canvas.getContext("2d");
// Check whether the current browser supports it
if ( ctx ) {
// Set the text size
ctx.font = "40px serif";
// Draw the fill text
ctx.fillText("hello word".100.100);
// Draw hollow text
ctx.strokeText("hello word".100.200);
} else {
console.log("Your current browser does not support Canvas");
}
</script>
</body>
</html>
Copy the code
[Effect drawing]
In the example above, I used a font property to change the size of the text. Canvas provides four styles for setting text properties. Font is the same as the FON property in CSS. TextAlign sets the text alignment: start, end, left, right, or Center. The default is Start. TextBaseline sets the alignment of the baseline: top, Hanging, middle, alphabetic, ideographic, and bottom. The default is Alphabetic. Direction Sets the direction of the text: LRT, RTL, inherit
4. Implement a simple line chart
[analysis]
-
X scale line
-
The bottom X-axis divides the Y-axis timeline data
-
Line chart position
First we need to implement a simple version of the line chart. The maximum is 300, and each scale on the X-axis is 50 degrees apart. Y wheelbase is divided into seven parts. After simple analysis, we need to draw three parts: line segment, text and dot. So we have three ways to implement it. Draw different content.
【 Draw a line segment 】
// The line segment method starts at xy and ends at xy. The default color is black
let line = ( startX, startY, endX, endY, color = "# 000" ) = > {
// Set the color
ctx.strokeStyle = color;
// Generate a path
ctx.beginPath();
// Set the stroke
ctx.moveTo(startX,startY);
/ / first
ctx.lineTo(endX, endY);
// Close the path
ctx.closePath();
ctx.stroke();
}
Copy the code
【 Draw text 】
// Draw the text text, draw the start coordinates, font size
let text = (text, x, y, fontSize = 16) = > {
// Set the text size
ctx.font = fontSize + 'px serif';
// Draw text
ctx.fillText(text, x, y);
}
Copy the code
【 Circle drawing 】
// Draw the position of the center point of the circle, radius
let round = ( x, y, r ) = > {
// Generate a path
ctx.beginPath();
/ / draw circle
ctx.arc(x, y, r, 0.Math.PI / 180 * 360.false);
ctx.stroke();
}
Copy the code
The auxiliary functions are all set up. Let’s now plot the x and y axes of the line chart. Let’s first determine the distance of the dividing line. The X-axis line needs to be separated from the total height/scale line = the dividing line distance. As I was writing, I suddenly realized that there was something wrong with this calculation rule. It’s a little awkward. Math is tough
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
<title>Introduction to Canvas Foundation (4)</title>
<style>
#canvasBox{
border: 1px solid #ccc;
display: block;
margin: 100px auto;
}
</style>
</head>
<body>
<canvas width="500" height="500" id="canvasBox">Your browser does not support canvas tag rendering. Please open it in Google Chrome or Firefox</canvas>
<script type="text/javascript">
// Get the Canvas box
let canvas = document.getElementById("canvasBox");
// Get the canvas context object
let ctx = canvas.getContext("2d");
// Check whether the current browser supports it
if ( ctx ) {
// The line segment method starts at xy and ends at xy. The default color is black
let line = ( startX, startY, endX, endY, color = "# 000" ) = > {
// Set the color
ctx.strokeStyle = color;
// Generate a path
ctx.beginPath();
// Set the stroke
ctx.moveTo(startX,startY);
/ / first
ctx.lineTo(endX, endY);
// Close the path
// ctx.closePath();
ctx.stroke();
}
// Draw the text text, draw the start coordinates, font size
let text = (text, x, y, fontSize = 16) = > {
// Set the text size
ctx.font = fontSize + 'px serif';
// Draw text
ctx.fillText(text, x, y);
}
// Draw the position of the center point of the circle, radius
let round = ( x, y, r ) = > {
// Generate a path
ctx.beginPath();
/ / draw circle
ctx.arc(x, y, r, 0.Math.PI / 180 * 360.false);
ctx.stroke();
}
// Draw method
let polyline = () = > {
// Define the total height, width of the box, we define the canvas height to be 500, here we take 400
let H = 400,
W = 400;
// Get the distance between the x axes
let X = parseInt(400 / 7);
// Get the distance between Y axes
let Y = parseInt(400 / 8);
// Draw the polyline data
let lineData = [50.130.150.88.250.33.300];
// Time line data
let timeData = ['Mon'.'Tue'.'Wed'.'Thu'.'Fri'.'Sat'.'Sun'];
// Draw the X-axis line
[7.6.5.4.3.2.1].forEach((item, index) = > {
Draw a line / /
line(50.50 + X * index, W, 50 + X * index, item === 1 ? "# 000" : "#ccc" );
console.log(50 + X * index)
// Mark the scale value
text((item - 1) * 50.20.56 + X * index);
})
// Draw a time line
for ( let i = 0, len = timeData.length + 1; i < len; i++ ) {
Draw a line / /
line(50 + Y * i,X * 6 + 50.50 + Y * i, X * 6 + 50 + 10);
if ( len - 1 > i ) {
// Mark the calibration time
text(timeData[i], 65 + Y * i, X * 6 + 65.13); }}// Draw a line graph
lineData.forEach(( item, index ) = > {
if ( index === 0 ) {
ctx.moveTo(50 + Y * (index + 1), 400 - item - 14 );
ctx.lineTo(50 + Y * (index + 1), 400 - item - 14 );
} else {
ctx.lineTo(50 + Y * (index + 1), 400 - item - 14 );
}
ctx.stroke();
})
}
polyline();
} else {
console.log("Your current browser does not support Canvas");
}
</script>
</body>
</html>
Copy the code
[Effect drawing]
The advanced version doesn’t have time to implement. Suddenly close to work, the project. It’s up to the big guys to make it happen.