preface

Canvas is a new tag element for H5. Canvas means a canvas on which we can draw graphics through JS. Application scenarios, such as movement tracks, portraits, personalized posters, cool effects and so on.

Fundamentals & Concepts

Create a Canvas

<canvas id="myCanvas" width="200" height="100"></canvas>
Copy the code

Note: The default canvas size is 300*150. You can’t use CSS to change the size. You can use the canvas’s label properties width and height to change the size. Canvas is a double tag.

Compatibility and Support

Mozilla applications support canvas starting with Gecko 1.8 (Firefox 1.5) and Internet Explorer with Canvas starting with IE9. Chrome and Opera 9+ also support canvas.

<canvas>Your browser does not support Canvas, please upgrade your browser.</canvas>
Copy the code

Test support

var canvas = document.getElementById('tutorial');
if (canvas.getContext){
  var ctx = canvas.getContext('2d');
  // Start drawing
} else {
  // No canvas support
}
Copy the code

Note: Browsers that support < Canvas > will only render the

tag, ignoring the text content. Browsers that do not support

will display text directly; Of course, this text can also be replaced with an image.

Render context

The getContext() method here can be understood as a toolbox, and we can use the tools inside to draw the graph.

var mycanvas = document.getElementById('mycanvas');
// Get the 2D context object
var ctx = mycanvas.getContext('2d');
Copy the code

Start drawing a line

Q1: Think about it. Why do you have a beginning and an end?

/ / starting point
ctx.moveTo(100.100)
/ / the end
ctx.lineTo(200.100)
Q2: What is strock() here?
ctx.stroke();
Copy the code

Draw shapes (Q1)

There are two ways to draw a canvas element (F-q2)

context.fill()// Close the graph fill
context.stroke()// Line segment stroke
Copy the code

The pixel grid

(F-Q1): Canvas element is overwritten by grid by default. Generally speaking, a cell in a grid is equivalent to a pixel in a Canvas element. The grid starts at the upper-left corner and coordinates (0,0). All elements are positioned relative to the origin.

Draw the path

As I said, the lattice of pixels makes up our canvas, so the path can be understood as the set of all the canvas pairs of pixels, except that we specify the path path and the color of the pixels, and any path is closed.

Steps:

  • Create a path start point
  • Call the draw method to draw the path
  • Close the path
  • Once the path is generated, render the graph by stroke or filling the path area.

Draw the line

    /* Draw a line */
    if (mycanvas.getContext) {
      // Each Canvas node has a corresponding context object. To get this object, the method is getCotext
      let ctx=mycanvas.getContext("2d");
      // Start drawing
      ctx.beginPath();
      // Set the starting coordinates of the path
      ctx.moveTo(50.50);
      // Draw a line to coordinate 50 150
      ctx.lineTo(150.50);
      // Line color, stroke
      ctx.stroke();
      // Close the drawing (close the path)
      ctx.closePath();  
    } else {
      alert("Browser not supported")}Copy the code

Draw a rectangle

Pay attention to the fillStyle fillRect() strokeEect() property and method use;

   /* Draw a rectangle */
    if (mycanvas.getContext) {
      let ctx = mycanvas.getContext("2d");
      ctx.beginPath();
      // Set the fill color
      ctx.fillStyle = '#cfa';
      // ctx.fillrect fills (x, y, width, height) the initial coordinate value and the width and height of the rectangle
      ctx.fillRect(500.100.200.100);
      // The clearRect method is used to clear the contents of a rectangular area, the starting coordinates of (x, y, width, height) and the width and height of the rectangle
      ctx.clearRect(525.125.50.50)
      //ctx.strokeRect stroke, ctx.strokeStyle Stroke color
      ctx.strokeStyle = 'red'
      ctx.strokeRect(50.50.100.100);
      ctx.closePath(); 
    } else {
      alert("Browser not supported")}Copy the code

The result is as follows:

【 note 】

Draw circles (hollow circles are drawn by default)

   if (mycanvas.getContext) {
      let ctx = mycanvas.getContext("2d");
      ctx.beginPath();
      Radius is the radius, startAngle and endAngle are the starting and ending angles of the sector (expressed in radians), and anticlockwise indicates whether the graph should be drawn anticlockwise or anticlockwise.
      //ctx.arc(x, y, radius, startAngle, endAngle, anticlockwise);
      ctx.arc(200.400.100.0.Math.PI * 2.true);
      // ctx.fillStyle = "#cfa";
      ctx.stroke();/ / the hollow circle
      // ctx.fill(); / / solid circle
      ctx.closePath();
    } else {
      alert("Browser not supported")}Copy the code

Note: Radians =(math.pi /180)* Angle. Can we use this to draw a sector?

Special effects

Draw line gradient

Before we can use CSS gradient to achieve line gradient, let’s try to use this to achieve gradient.

    if (mycanvas.getContext) {
      let ctx = mycanvas.getContext("2d");
      // The createLinearGradient method takes (x1, y1, x2, y2),
      // where x1 and y1 are the starting coordinates, x2 and y2 are the ending coordinates.
      // With different coordinates, you can generate gradients from top to bottom, left to right, and so on.
      var myGradient = ctx.createLinearGradient(10.10.610.30);
      myGradient.addColorStop(0."red");
      myGradient.addColorStop(0.5."green");
      myGradient.addColorStop(1."blue");
      ctx.fillStyle = myGradient;
      // Draw a rectangle
      ctx.fillRect(10.10.600.20);
    } else {
      alert("Browser not supported")}Copy the code

Effect:

Draw the shadow

    // * Draw a shadow */
    if (mycanvas.getContext) {
      let ctx = mycanvas.getContext("2d");
      ctx.shadowOffsetX = 5; // Set the horizontal displacement
      ctx.shadowOffsetY = 5; // Set the vertical displacement
      ctx.shadowBlur = 5; // Set the ambiguity
      ctx.shadowColor = "Rgba (0,0,0,0.5)"; // Set the shadow color
      ctx.fillStyle = "#CC0000";
      ctx.fillRect(10.600.110.20);
    } else {
      alert("Browser not supported")}Copy the code

Effect:

Draw text

Canvas has two ways to render text

fillText(text, x, y [, maxWidth])
// Fill the specified text at the specified (x,y) position. The maximum width to draw is optional.
Copy the code
strokeText(text, x, y [, maxWidth])

// Draws a text border (text) at the specified (x,y) position. The maximum width to draw is optional.
Copy the code

Example (think about what is the use of drawing text? Q3)

var ctx;
function draw(){
    var canvas = document.getElementById('tutorial');
    if(! canvas.getContext)return;
    ctx = canvas.getContext("2d");
    ctx.font = "100px sans-serif"
    ctx.fillText("What's the use of drawing text?".10.100);
    ctx.strokeText("What's the use of drawing text?".10.200)
}
draw();
Copy the code

Draw pictures

We can also draw images directly on canvas; Pay attention to adjust the width and height of the canvas to match the picture, the effect will be better.

create<img>The element

var image = new Image();
image.src = "images/tu.jpg"
Copy the code

drawimg

// Parameters 1: the img parameters to draw 2, 3: the canvas coordinates of the img to draw
ctx.drawImage(img,0.0); 
Copy the code

Note: Considering that the image is loaded from the network, if the image is not fully loaded by the time you drawImage, do nothing and some browsers will throw an exception. So we should make sure that we don’t draw the image until after the IMG has been drawn.

var img = new Image();   // Create the img element
img.src = 'myImage.png'; // Set the image source address
img.onload = function(){
  ctx.drawImage(img, 0.0)}Copy the code

drawimgThe image in the tag element

<img src="./tu.jpg" alt="" width="300"><br>
<canvas id="tutorial" width="600" height="400"></canvas>
<script type="text/javascript">
    function draw(){
        var canvas = document.getElementById('tutorial');
        if(! canvas.getContext)return;
        var ctx = canvas.getContext("2d");
        var img = document.querySelector("img");
        ctx.drawImage(img, 0.0);
    }
    document.querySelector("img").onclick = function (){
        draw();
    }
</script>

Copy the code

Zoom pictures

DrawImage (image, x, y, width, height);

This method has two additional arguments: width and height, which control how much to scale when drawing to the canvas.

ctx.drawImage(img, 0.0.400.200)
Copy the code

Draw picture + Draw Text — Case: Watermark (F-Q3)

1. Prepare canvas in HTML

<canvas id="myCanvas" width="1000" height="500" >Your browser does not support Canvas, please upgrade your browser.</canvas>
Copy the code

2. Load the image

var img = new Image();   
img.src = './img/demo.jpg'; 
Copy the code

3. Draw pictures

img.onload=function(){
    var canvas=document.getElementById("myCanvas");
    var ctx=canvas.getContext("2d");
    ctx.drawImage(img,0.0);
}
Copy the code

After drawing the picture on the canvas, go back to the onload function and continue to draw the watermark using the CTX object obtained in the previous step.

   ctx.font="20px microsoft yahei"; // Define the size and font of the watermark
   ctx.fillStyle = "Rgba (255255255,0.5)";  // Customize the color and transparency of the watermark
   ctx.fillText("my images".100.100); // Finish filling the watermark and locating the watermark position
Copy the code

The source code

<canvas id="myCanvas" width="1000" height="500" >
	Your browser does not support the HTML5 canvas tag.
</canvas>
<script>
    // Prepare the img object
    var img = new Image();   
    img.src = './img/demo.jpg';
    // Start drawing after loading
    img.onload=function(){
       // Prepare the canvas environment
       var canvas=document.getElementById("myCanvas");
       var ctx=canvas.getContext("2d");
       // Draw a picture
       ctx.drawImage(img,0.0);
       // Create a watermark
       ctx.font="20px microsoft yahei";
       ctx.fillStyle = "Rgba (255255255,0.5)";
       ctx.fillText("Onion Watermark".100.100);
    }
</script>
Copy the code

Effect: