1. Overview of Canvas
- Canvas draws 2D graphics on Web pages through JavaScript. Canvas is rendered pixel by pixel. Developers can draw arbitrarily through JavaScript scripts. There are several ways to use canvas elements to draw paths, rectangles, circles, characters, and add images.
- In Canvas, once the drawing is completed, it will not continue to get the attention of the browser. If the position of any object has changed, it may also need to be redrawn.
2. Canvas basic usage
<canvas id="tutorial" width="300" height="300"></canvas>
Elements < 1.2
- canvas is a two-dimensional mesh.
The coordinates of the upper left corner of the canvas are (0,0) - < canvas > looks the same as the < img > tag, except that < canvas > has only two optional attributes, width and height, but not src and alt. If the width and height attributes are not set for < canvas >, the default width and height are 300 and 150, both in px. You can also use css attribute to set the width and height, but if the width and height attribute is inconsistent with the initial scale, it will be distorted. Therefore, it is recommended that you never use the css attribute to set the width and height of < canvas >.
- Because some older browsers (especially ie before IE9) or browsers do not support HTML elements < canvas >, you should always be able to display alternative content on these browsers. Browsers that support < canvas > will only render < canvas > tags, ignoring the alternatives.
Browsers that do not support < canvas > will directly render alternative content:
<canvas> Your browser does not support canvas,Please upgrade your browser. </canvas>
Replace with < img >:
<canvas> <img src="" alt=""> </canvas>
- The end tag < / Canvas > cannot be omitted.
2.2. Three rendering context
< / Canvas > creates a fixed size canvas, exposes one or more rendering contexts (brushes), and uses the rendering context to draw and process the content to be displayed.
We focus on 2D rendering context. For example, WebGL uses the 3D context based on OpenGL ES ("experimental WebGL").
var canvas = document.getElementById('tutorial'); //Get 2d context object var ctx = canvas.getContext('2d');
2.3. Test support
var canvas = document.getElementById('tutorial'); if (canvas.getContext){ var ctx = canvas.getContext('2d'); // drawing code here } else { // canvas-unsupported code here }
- Example: draw two rectangles
<canvas id="tutorial" width="300" height="300"></canvas> <script type="text/javascript"> function draw(){ var canvas = document.getElementById('tutorial'); if(!canvas.getContext) return; var ctx = canvas.getContext("2d"); ctx.fillStyle = "rgb(200,0,0)"; //draw rectangle ctx.fillRect (10, 10, 55, 50); ctx.fillStyle = "rgba(0, 0, 200, 0.5)"; ctx.fillRect (30, 30, 55, 50); } draw(); </script>
3. Draw triangles with different line colors
3.1. Draw triangle
3.1.1 draw a simple triangle
<script type="text/javascript"> // Get canvas element var example = document.getElementById('example') // Get Toolset var ctx = example.getContext('2d') // Locate a starting point ctx.moveTo(50, 50) // Draw the second point ctx.lineTo(100, 50) // Draw the third point ctx.lineTo(75, 100) // Connection start point / closed path // ctx.lineTo(50, 50) ctx.closePath() // Draw line ctx.stroke() </script>
3.1.2 draw a triangle with different border colors
- Drawn color and line width
// Sets the width of the line in pixels ctx.linewidth = number // Sets the color of the stroke graphic ctx.strokeStyle = color // Sets the color of the filled drawing ctx.fillStyle = color
- Closed path
// Start a path, or reset the current path, and cut off the path connection with the previous drawing. ctx.beginPath() * Advantages of closed path You can draw graphics of different sizes and colors separately.
<script type="text/javascript"> // Get canvas element var example = document.getElementById('example') // Get Toolset var ctx = example.getContext('2d') // 1. Draw the first point // Sets the color of the drawing ctx.strokeStyle = 'pink' // Sets the line width of the drawing ctx.lineWidth = 4 ctx.moveTo(50, 50) ctx.lineTo(100, 50) // Reset current path // Draw line ctx.stroke() ctx.beginPath() // 2. Draw the second point ctx.strokeStyle = 'orange' ctx.lineWidth = 4 ctx.moveTo(100, 50) ctx.lineTo(75, 100) ctx.stroke() ctx.beginPath() // 3. Draw the third point ctx.strokeStyle = 'blue' ctx.lineWidth = 4 ctx.moveTo(75, 100) ctx.lineTo(50, 50) ctx.stroke() // ctx.beginPath() </script>
3.2. Draw words and pictures
- Specify location
// Draws text within the specified position and width ctx.fillText(text, x, y, maxwidth)
- Set font name and style
// Set font name and shape ctx.font="Font properties" // bold 32px sans-serif
- Set font alignment position
// Set horizontal alignment of text content ctx.textAlign='Horizontal orientation' // center\left\right // Set vertical alignment of text content ctx.textBaseLine='Vertical azimuth value' // top\middle\bottom
- Save drawing content as picture
// Save the current drawing content as a picture ctx.toDataURL(type, encoderOptions) // image/png picture format, picture quality between 0 and 1
<script type="text/javascript"> // Get canvas element var example = document.getElementById('example') // Get Toolset var ctx = example.getContext('2d') // Style text (before drawing) ctx.font = "bold 20px Blackbody" // These codes are just easy to distinguish between text positions ctx.strokeStyle = "pink" ctx.moveTo(10, 30) ctx.lineTo(120, 30) ctx.stroke() ctx.beginPath() ctx.moveTo(30, 10) ctx.lineTo(30, 120) ctx.stroke() ctx.beginPath() ctx.moveTo(10, 60) ctx.lineTo(120, 60) ctx.stroke() ctx.beginPath() ctx.moveTo(60, 10) ctx.lineTo(60, 120) ctx.stroke() // level ctx.textAlign = "center" // vertical ctx.textBaseline = "middle" // Call the API in the toolset to draw text // First (filled) ctx.fillText('written words', 30, 30) // Second (stroke) ctx.strokeText('paint brush', 60, 60) // Save the drawn content as a picture (a base64 character set will be returned) var imgUrl = example.toDataURL('image/png', 1) console.log(imgUrl); </script>
3.3 draw rectangle, circle and picture
- draw rectangle
// 1. Draw the path of the rectangle first, then stroke or fill ctx.rect(x, y, width, height); ctx.stroke() // or ctx.fill() // 2. Draw rectangles without / with filling directly ctx.strokeRect(x,y,width,height) ctx.fillRect(x,y,width,height)
- Draw a circle with radians
// Draw a circle at the specified position ctx.arc(x,y,startAngle,endAngle,clockwise) // Take (x, y) as the center and r as the radius, starting from startAngle radian to ending angle radian. anticlosewise is a Boolean value. true indicates counterclockwise and false indicates clockwise (clockwise by default).
- Draw pictures of different sizes
// Draw a fixed coordinate image on the canvas ctx.drawImage(img,x,y); // Drawing an image on the canvas not only fixes the coordinates, but also specifies the width and height of the image ctx.drawImage(img,x,y,width,height) // Cut the image on the canvas and draw the cut part on the canvas ctx.drawImage(img,sx,sy,swidth,sheight,x,y,width,height)
4. Scraping card case
There are three steps:
- Draw random winning information into the canvas
- Use a gray rectangle to cover the winning information
- Use the mouse to scratch the area to achieve the effect of scraping
<script type="text/javascript"> // Get canvas element var example = document.getElementById('example') // Get Toolset var ctx = example.getContext('2d') // Define an array of winning information var prices = ['be promoted step by step', 'Happiness', 'wishing you prosperity', 'Money and treasures will be plentiful'] ctx.fillStyle = 'red' ctx.font = 'bold 36px Blackbody' ctx.textAlign = 'center' ctx.textBaseline = 'middle' // Randomly generate a winning information element and draw it in the middle of the canvas ctx.fillText(prices[Math.floor(Math.random() * prices.length)], example.width / 2, example.height / 2) // Save the drawn winning information as a picture and use it as the background picture of canvas elements var imgUrl = example.toDataURL('image/png', 1) example.style.background = 'url(' + imgUrl + ')'; // Draw a rectangle to cover the winning information ctx.clearRect(0, 0, example.width, example.height) // Sets the drawing color of the rectangle ctx.fillStyle = '#ddd' // Draw the covered area ctx.fillRect(0, 0, example.width, example.height) var flag = false example.onmousedown = function () { flag = true ctx.globalCompositeOperation = 'destination-out'; } example.ontouchstart = function () { flag = true ctx.globalCompositeOperation = 'destination-out'; } example.onmousemove = function (e) { if (flag) { console.log(e); var x = e.offsetX var y = e.offsetY ctx.fillStyle = 'pink' ctx.fillRect(x, y, 30, 30) } } example.ontouchmove = function (e) { if (flag) { console.log(e); var x = e.touches[0].clientX var y = e.touches[0].clientY ctx.fillStyle = 'pink' ctx.fillRect(x, y, 30, 30) } } example.onmouseleave = function () { flag = false } example.ontouchend = function () { flag = false } </script>