1. Introduction to Canvas
Canvas API (canvas) is a new tag in HTML5 for real-time generation of images on web pages, and can manipulate image content, basically it is a bitmap (bitmap) that can be manipulated by JavaScript. The Canvas object represents an HTML canvas element <canvas>. It has no behavior of its own, but defines an API to support scripted client-side drawing operations.
2. Create a Canvas canvas
That is, add a canvas element to the HTML5 page, specify the id, width (width) and height (height) of the element, the sample code is as follows:
Maximum Canvas Size
browser | maximum height | maximum width | maximum area |
---|---|---|---|
Chrome | 32,767 pixels | 32,767 pixels | 268,435,456 pixels (i.e., 16,384 x 16,384) |
Firefox | 32,767 pixels | 32,767 pixels | 268,435,456 pixels (i.e., 16,384 x 16,384) |
Safari | 32,767 pixels | 32,767 pixels | 268,435,456 pixels (i.e., 16,384 x 16,384) |
IE | 8,192 pixels | 32,767 pixels | ? |
- Height (height) and width (width) can be defined in CSS
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Canvas Draw a dynamic starry sky</title> </head> <body> <style> canvas { position: absolute; margin: 0; padding: 0; background-size: cover; width: 100%; height: 100%; } body { height: 100%; margin: 0; /* overflow: hidden; */ } </style> <canvas id="canvas"></canvas> </body> </html>
- Direct definition of height (height) and width (width)
<canvas id="myCanvas" width="200″ height="100″></canvas>
3. Common methods of Canvas
method
getElementById("canvas") use id to find canvas element getContext("2d") objects are built-in HTML5 Object with various methods for drawing paths, rectangles, circles, characters and adding images. createRadialGradient() Draw a rectangle and radially/Fill the circle with a gradient addColorStop() specifies the color and stop position in the gradient object createLinearGradient() Create linear gradients (used on canvas content) createPattern() Repeats the specified element in the specified direction rect() create rectangle fillRect() Draw the "filled" rectangle strokeRect() draw rectangle (no fill) clearRect() Clears the specified pixels within the given rectangle fill() Fill current drawing (path) stroke() draw the defined path beginPath() start a path, or reset the current path moveTo() Moves the path to the specified point in the canvas without creating a line closePath() Create a path from the current point back to the starting point lineTo() Adds a new point, then creates a line in the canvas from that point to the last specified point clip() Cut areas of any shape and size from the original canvas quadraticCurveTo() Create quadratic Bézier curves bezierCurveTo() Create Cubic Bézier Curves arc() create arc/Curves (for creating circles or partial circles) arcTo() Create an arc between two tangents/curve isPointInPath() Returns if the specified point is within the current path true,otherwise return false scale() Scale the current drawing to be larger or smaller rotate() rotate current drawing translate() Remap the canvas on (0,0) Location transform() replace the plot's current transformation matrix setTransform() Reset the current transformation to the identity matrix. then run transform() fillText() Draw "filled" text on the canvas strokeText() Draw text on canvas (no padding) measureText() Returns an object containing the specified text width drawImage() Draw an image, canvas or video onto the canvas createImageData() Create new, blank ImageData object getImageData() return ImageData object that copies the pixel data for the specified rectangle on the canvas putImageData() Put the image data (from the specified ImageData object) back on the canvas
Attributes
- width: returns the width of the ImageData object
- height: returns the height of the ImageData object
- data: returns an object containing the image data of the specified ImageData object
- fillStyle: Sets or returns the color, gradient or pattern used to fill the painting
- strokeStyle: Sets or returns the color, gradient or pattern used for the stroke
- shadowColor: Sets or returns the color used for shadows
- shadowBlur: Sets or returns the blur level used for shadows
- shadowOffsetX: Set or return the horizontal distance of the shadow from the shape
- shadowOffsetY: Set or return the vertical distance of the shadow from the shape
- lineCap: Set or return the end cap style of the line
- lineJoin: Sets or returns the type of corner created when two lines intersect
- lineWidth: set or return the current line width
- miterLimit: set or return the maximum miter length
- font: set or return the current font property of the text content
- textAlign: Set or return the current alignment of the text content
- textBaseline: Sets or returns the current text baseline used when drawing text
- globalAlpha: Sets or returns the current alpha or transparency value of the drawing
- globalCompositeOperation: Sets or returns how new images are drawn onto existing images
4. Drawing with JavaScript
"use strict"; var canvas = document.getElementById('canvas'), ctx = canvas.getContext('2d'), w = canvas.width = window.innerWidth, h = canvas.height = window.innerHeight, hue = 217, stars = [], count = 0, maxStars = 1000; // Cache gradient var canvas2 = document.createElement('canvas'), ctx2 = canvas2.getContext('2d'); canvas2.width = 100; canvas2.height = 100; var half = canvas2.width / 2, gradient2 = ctx2.createRadialGradient(half, half, 0, half, half, half);//Draw a rectangle and fill it with a radial/circular gradient gradient2.addColorStop(0.025, '#fff');//Define a gradient from black to white as the filling style of the rectangle gradient2.addColorStop(0.1, 'hsl(' + hue + ', 61%, 33%)'); gradient2.addColorStop(0.25, 'hsl(' + hue + ', 64%, 6%)'); gradient2.addColorStop(1, 'transparent'); ctx2.fillStyle = gradient2; ctx2.beginPath(); ctx2.arc(half, half, half, 0, Math.PI * 2); ctx2.fill(); // End cache function random(min, max) { if (arguments.length < 2) { max = min; min = 0; } if (min > max) { var hold = max; max = min; min = hold; } return Math.floor(Math.random() * (max - min + 1)) + min; } var Star = function() { this.orbitRadius = random(w / 2 - 50); this.radius = random(100, this.orbitRadius) / 10; this.orbitX = w / 2; this.orbitY = h / 2; this.timePassed = random(0, maxStars); this.speed = random(this.orbitRadius) / 1000000; this.alpha = random(2, 10) / 10; count++; stars[count] = this; } Star.prototype.draw = function() { var x = Math.sin(this.timePassed + 1) * this.orbitRadius + this.orbitX, y = Math.cos(this.timePassed) * this.orbitRadius / 2 + this.orbitY, twinkle = random(10); if (twinkle === 1 && this.alpha > 0) { this.alpha -= 0.05; } else if (twinkle === 2 && this.alpha < 1) { this.alpha += 0.05; } ctx.globalAlpha = this.alpha; ctx.drawImage(canvas2, x - this.radius / 2, y - this.radius / 2, this.radius, this.radius); this.timePassed += this.speed; } for (var i = 0; i < maxStars; i++) { new Star(); } function animation() { ctx.globalCompositeOperation = 'source-over'; ctx.globalAlpha = 0.8; ctx.fillStyle = 'hsla(' + hue + ', 64%, 6%, 1)'; ctx.fillRect(0, 0, w, h) ctx.globalCompositeOperation = 'lighter'; for (var i = 1, l = stars.length; i < l; i++) { stars[i].draw(); }; window.requestAnimationFrame(animation); } animation();