⑭ A series of usage methods of HTML5 canvas

Html5

I am a novice, write down blog for self review, self summary.
If there are any mistakes, please point them out.
Source of learning materials: shangsilicon Valley

Use picture & set background

Insert picture in canvas (image object required):
1. When canvas operates pictures, it must wait until the pictures are loaded
2.drawImage(image, x, y, width, height)
Where image is the image or canvas object, and x and y are its starting coordinates in the target canvas. The two parameters, width and height, are used to control the size that should be scaled when canvas is drawn in.

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title></title>
  <style type="text/css">
    * {
      margin: 0;
      padding: 0;
    }

    html, body {
      height: 100%;
      overflow: hidden;
    }

    body {
      background: pink;
    }

    #test {
      background: gray;
      position: absolute;
      left: 0;
      top: 0;
      right: 0;
      bottom: 0;
      margin: auto;
    }
  </style>
</head>
<body>
<canvas id="test" width="300" height="300">
  <span>Your browser does not support canvas elements</span>
</canvas>
</body>
<script type="text/javascript">
  window.onload = function () {
    var canvas = test;
    if (canvas.getContext) {
      var ctx = canvas.getContext("2d");

      var img = new Image();
      // Specify picture path
      img.src = "tg.png";
      img.onload = function () {
        draw();
      }

      function draw() {
        ctx.drawImage(img, 0, 0, img.width, img.height)
      }
    }
  }
</script>
</html>

Set the background in canvas (image object required):
createPattern(image, repetition)
Image: image source
The following options are available for the iteration:
"repeat"
"repeat-x"
"repeat-y"
"no-repeat"

In general, we use the object returned by createPattern as the value of fillstyle

  window.onload = function () {
    var canvas = test;
    if (canvas.getContext) {
      var ctx = canvas.getContext("2d");

      var img = new Image();
      img.src = "tg.png";
      img.onload = function () {
        draw();
      }

      function draw() {
        var pattern = ctx.createPattern(img, "no-repeat")
        ctx.fillStyle = pattern;
        ctx.fillRect(0, 0, 300, 300);
      }
    }
  }

Gradient effect

canvas linear gradient
createLinearGradient(x1, y1, x2, y2)
Represents the start (x1,y1) and end (x2,y2) of the gradient

gradient.addColorStop(position, color)
Gradient: return value of createlineargradient
The addColorStop method takes two parameters,
The position parameter must be a value between 0.0 and 1.0, indicating the relative position of the color in the gradient.
For example, 0.5 means that the color will appear in the middle.
The color parameter must be a valid CSS color value (for example, FFF, rgba(0,0,0,1))

  window.onload = function () {
    var canvas = test;
    if (canvas.getContext) {
      var ctx = canvas.getContext("2d");

      var gradient = ctx.createLinearGradient(0, 0, 200, 200);
      gradient.addColorStop(0, "red");
      gradient.addColorStop(0.5, "yellow");
      gradient.addColorStop(0.7, "black");
      gradient.addColorStop(1, "green");
      ctx.fillStyle = gradient;
      ctx.fillRect(0, 0, 300, 300);
    }
  }

canvas radial gradient
createRadialGradient(x1, y1, r1, x2, y2, r2)
The first three parameters define another circle with (x1,y1) as the origin and r1 as the radius,
The last three parameters define another circle with (x2,y2) as the origin and r2 as the radius.

  window.onload = function () {
    var canvas = test;
    if (canvas.getContext) {
      var ctx = canvas.getContext("2d");
      var gradient = ctx.createRadialGradient(150, 150, 50, 150, 150, 100)
      gradient.addColorStop(0, "red");
      gradient.addColorStop(0.5, "yellow");
      gradient.addColorStop(0.7, "pink");
      gradient.addColorStop(1, "green");
      ctx.fillStyle = gradient;
      ctx.fillRect(0, 0, 300, 300);
    }
  }

Draw text

canvas provides two ways to render text:

fillText(text, x, y)
Fills the specified text in the specified (x,y) position
strokeText(text, x, y)
Draws a text border at the specified (x,y) position

Note that the default font of text style font is 10px sans serif.
Font attribute must have both size and font when specified.

  window.onload = function () {
    var canvas = test;
    if (canvas.getContext) {
      var ctx = canvas.getContext("2d");
      ctx.fillStyle = "green"
      ctx.font = "40px sans-serif"
      ctx.fillText("csdn", 100, 100);
      ctx.strokeText("csdn", 100, 100);
    }
  }

textAlign
Text alignment options. Optional values include:
Left: align text left.
Right: align text to the right.
Center: center text.
textAlign="center" here is special. When the value of textAlign is center:
The center of the text is based on the value of x you give when you fill text, that is, half of the text is to the left of X, half is to the right of X

  window.onload = function () {
    var canvas = test;
    if (canvas.getContext) {
      var ctx = canvas.getContext("2d");
      ctx.fillStyle = "green";
      ctx.font = "40px sans-serif";
      ctx.textAlign = "center";
      ctx.fillText("csdn", 50, 50);
    }
  }

textBaseline
Describes the properties of the current text baseline when drawing text.
top
The text baseline is at the top of the text block.
middle
The text baseline is in the middle of the text block.
bottom
The text baseline is at the bottom of the text block.

  window.onload = function () {
    var canvas = test;
    if (canvas.getContext) {
      var ctx = canvas.getContext("2d");
      ctx.fillStyle = "green";
      ctx.font = "40px sans-serif";
      ctx.textBaseline = "middle";
      ctx.fillText("csdn", 0, 0);
    }
  }


measureText
The measureText() method returns a TextMetrics object that contains information about the size of the text (such as the width of the text)

  window.onload = function () {
    var canvas = test;
    if (canvas.getContext) {
      var ctx = canvas.getContext("2d");
      ctx.fillStyle = "green";
      ctx.font = "60px sans-serif";
      ctx.fillText("csdn", 50, 50);
      var obj = ctx.measureText("csdn");
      console.log(obj);
    }
  }

For example: the text in canvas is horizontally and vertically centered

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title></title>
  <style type="text/css">
    * {
      margin: 0;
      padding: 0;
    }

    body {
      background: black;
    }

    #c1 {
      background: white;
    }
  </style>
</head>
<body>
	<canvas id="c1" width="400" height="400"></canvas>
</body>
<script type="text/javascript">
  window.onload = function () {
    var oC = c1;
    var oGC = oC.getContext('2d');
    oGC.font = '60px impact';
    oGC.textBaseline = 'middle';
    var w = oGC.measureText('CSDN').width;
    oGC.fillText('CSDN', (oC.width - w) / 2, (oC.height - 60) / 2);
  };
</script>
</html>

Shadow (text shadow & box model shadow)

shadowOffsetX shadowOffsetY
shadowOffsetX and shadowOffsetY are used to set the extension distance of shadows on the X and Y axes,
They are all 0 by default.
shadowBlur
shadowBlur is used to set the blur level of shadows. Its value is not related to the number of pixels or affected by the transformation matrix. It is 0 by default.
Shadowcolor (required)
shadowColor is the standard CSS color value, which is used to set the shadow color effect. The default is full transparent black.

  window.onload = function () {
    var oC = c1;
    var oGC = oC.getContext('2d');

    //Text shadow & box shadow
    oGC.shadowOffsetX = 20;
    oGC.shadowOffsetY = 20;
    oGC.shadowBlur = 30;
    oGC.shadowColor = "yellow";

    oGC.fillRect(0, 0, 100, 100);
  };

Pixel operation

Pixel operation in canvas:
So far, we haven't thoroughly understood the principle of Canvas real pixels. In fact, you can directly manipulate pixel data through ImageData object, directly read or write data array into the object

getImageData() gets an ImageData object containing the pixel data of the canvas scene, which represents the object data of the canvas region.
ctx.getImageData(sx, sy, sw, sh)
sx: the x coordinate of the upper left corner of the rectangular area of the image data to be extracted.
sy: the y coordinate of the upper left corner of the rectangular area of the image data to be extracted.
sw: the width of the rectangular area of image data to be extracted.
sh: the height of the rectangular area of image data to be extracted.

The ImageData object stores the real pixel data of the canvas object, which contains the following read-only attributes:
Width: picture width, in pixels
Height: the height of a picture, in pixels
data:Uint8ClampedArray Type,
Contains integer data in RGBA format, ranging from 0 to 255 (including 255)
R: 0 -- > 255 (black to white)
G: 0 -- > 255 (black to white)
B: 0 -- > 255 (black to white)
A: 0 -- > 255 (transparent to opaque)

putImageData() method is used to write pixel data to the scene.
putImageData(myImageData, dx, dy)
The dx and dy parameters represent the device coordinates of the pixel data you want to draw in the upper left corner of the scene

  window.onload = function () {
    var canvas = test;
    if (canvas.getContext) {
      var ctx = canvas.getContext("2d");
      /*imageData
        width:Number of pixels horizontally
        height:Number of pixels vertically
        data:array
          rgba information of each pixel
      */
	  // 100 * 100 10000 pixels
      var imageData = ctx.getImageData(0, 0, 100, 100);
      for (var i = 0; i < imageData.data.length; i++) {
        imageData.data[4 * i + 3] = 100;
      }
      ctx.putImageData(imageData, 0, 0)
    }
  }


Create an ImageData object
ctx.createImageData(width, height);
Width: the width of the imagedata new object.
Height: the height of the imagedata new object.
Transparent is created by default

  window.onload = function () {
    var canvas = test;
    if (canvas.getContext) {
      var ctx = canvas.getContext("2d");
      //Create RGBA by default (0,0,0,0)
      var imageData = ctx.createImageData(100, 100);
      for (var i = 0; i < imageData.data.length; i++) {
        imageData.data[4 * i + 3] = 255;
      }
      ctx.putImageData(imageData, 100, 100)
    }
  }

Example: operate on a single pixel (row and column)

  window.onload = function () {
    var canvas = test;
    if (canvas.getContext) {
      var ctx = canvas.getContext("2d");
      ctx.save();
      ctx.fillStyle = "pink";
      ctx.beginPath();
      ctx.fillRect(50, 50, 100, 100);
      ctx.restore();

      var imgdata = ctx.getImageData(0, 0, canvas.width, canvas.height);
      for (var i = 0; i < imgdata.width; i++) {
        setPxInfo(imgdata, 30, i, [0, 0, 0, 255]);
      }
      ctx.putImageData(imgdata, 0, 0);
    }


    function getPxInfo(imgdata, x, y) {
      var color = [];

      var data = imgdata.data;
      var w = imgdata.width;
      var h = imgdata.height;

      //r
      color[0] = data[(y * w + x) * 4];
      //g
      color[1] = data[(y * w + x) * 4 + 1];
      //b
      color[2] = data[(y * w + x) * 4 + 2];
      //a
      color[3] = data[(y * w + x) * 4 + 3];

      return color;
    }

    function setPxInfo(imgdata, x, y, color) {
      var data = imgdata.data;
      var w = imgdata.width;
      var h = imgdata.height;

      //(x, y) x: how many columns Y: how many rows
      //r
      data[(y * w + x) * 4] = color[0];
      //g
      data[(y * w + x) * 4 + 1] = color[1];
      //b
      data[(y * w + x) * 4 + 2] = color[2];
      //a
      data[(y * w + x) * 4 + 3] = color[3];
    }
  }

Add a mosaic to the picture

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title></title>
  <style type="text/css">
    * {
      margin: 0;
      padding: 0;
    }

    html, body {
      height: 100%;
      overflow: hidden;
    }

    #msk {
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate3d(-50%, -50%, 0);
    }

  </style>
</head>
<body>
	<canvas id="msk"></canvas>
</body>
<script type="text/javascript">
  var oc = msk;
  if (oc.getContext) {
    var ctx = oc.getContext("2d");
    var img = new Image();
    img.src = "left01.jpg";
    img.onload = function () {
      oc.width = img.width;
      oc.height = img.height;
      draw();
    }

    function draw() {
      ctx.drawImage(img, 0, 0);

      var oldImgdata = ctx.getImageData(0, 0, img.width, img.height);
      var newImgdata = ctx.createImageData(img.width, img.height);
      //Mosaic
      /*
        1.Select a mosaic rectangle
        2.Extracting the information of a pixel randomly from the mosaic rectangle (rgba)
        3.Adjust the pixel information in the whole mosaic rectangle to the randomly selected one
      */
      //Select a mosaic rectangle
      var size = 5;
      for (var i = 0; i < oldImgdata.width / size; i++) {
        for (var j = 0; j < oldImgdata.height / size; j++) {
          //Math.random()  [0,1)
          //Math.random()*size  [0,5)
          //Math.floor(Math.random()*size) [0,4]
          //Extracting the information of a pixel randomly from the mosaic rectangle (rgba)
          var color = getPxInfo(oldImgdata, i * size + Math.floor(Math.random() * size), j * size + Math.floor(Math.random() * size));

          //Adjust the pixel information in the whole mosaic rectangle to the randomly selected one
          for (var a = 0; a < size; a++) {
            for (var b = 0; b < size; b++) {
              setPxInfo(newImgdata, i * size + a, j * size + b, color)
            }
          }
        }
      }
      ctx.clearRect(0, 0, oc.width, oc.height);
      ctx.putImageData(newImgdata, 0, 0);
    }

    function getPxInfo(imgdata, x, y) {
      var color = [];
      var data = imgdata.data;
      var w = imgdata.width;
      var h = imgdata.height;

      color[0] = data[(y * w + x) * 4];
      color[1] = data[(y * w + x) * 4 + 1];
      color[2] = data[(y * w + x) * 4 + 2];
      color[3] = data[(y * w + x) * 4 + 3];
      return color;
    }

    function setPxInfo(imgdata, x, y, color) {
      var data = imgdata.data;
      var w = imgdata.width;
      var h = imgdata.height;
      data[(y * w + x) * 4] = color[0];
      data[(y * w + x) * 4 + 1] = color[1];
      data[(y * w + x) * 4 + 2] = color[2];
      data[(y * w + x) * 4 + 3] = color[3];
    }
  }
</script>
</html>

synthesis

Setting of Global Transparency
This property affects the transparency of all graphics in canvas,
Valid values range from 0.0 (fully transparent) to 1.0 (fully opaque)
1.0 by default

  window.onload = function () {
    var canvas = test;
    if (canvas.getContext) {
      var ctx = canvas.getContext("2d");
      ctx.fillStyle = "red";
      ctx.globalAlpha = .5;
      ctx.fillRect(0, 0, 100, 100);
      ctx.fillRect(100, 100, 100, 100);
    }
  }

Overlay synthesis
Parameters for globalCompositeOperation:
Source over (default): the source is above, and the new image level is relatively high
Source in: leave only the overlap of source and target (the part of source)
Source out: leave only the part of the source exceeding the target
Source atop: cut off the overflow part of the source

Destination over: the target is above, the old image level is higher
Destination in: leave only the overlap of source and target (the part of target)
Destination out: leave only the part where the destination exceeds the source
Destination atop: cut off the overflow part of the target

  window.onload = function () {
    var canvas = test;
    if (canvas.getContext) {
      var ctx = canvas.getContext("2d");
      ctx.fillStyle = "pink";
      ctx.fillRect(50, 50, 100, 100);
      ctx.globalCompositeOperation = "destination-atop";
      ctx.fillStyle = "green";
      ctx.fillRect(100, 100, 100, 100);
    }
  }

Other uses

Export canvas as image todataurl (note method on canvas element interface)

  window.onload = function () {
    //Get the canvas
    var canvas = test;
    if (canvas.getContext) {
      var ctx = canvas.getContext("2d");
      ctx.fillRect(0, 0, 199, 199);
      var result = canvas.toDataURL();
      console.log(result);
    }
  }


Event action ctx.isPointInPath(x, y)
Determine whether detection points are included in the current path
x: X coordinate of detection point
y: Y coordinate of detection point

Note that this method only works on the newly drawn canvas image

  window.onload = function () {
    var canvas = test;
    if (canvas.getContext) {
      var ctx = canvas.getContext("2d");
      ctx.beginPath();
      ctx.arc(100, 100, 50, 0, 360 * Math.PI / 180);
      ctx.fill();

      ctx.beginPath();
      ctx.arc(200, 200, 50, 0, 360 * Math.PI / 180);
      ctx.fill();

      canvas.onclick = function (ev) {
        ev = ev || event;
        var x = ev.clientX - canvas.offsetLeft;
        var y = ev.clientY - canvas.offsetTop;
        if (ctx.isPointInPath(x, y)) {
          alert(123);
        }
      }
    }
  }

Tags: Javascript html5 Attribute

Posted on Thu, 04 Jun 2020 07:11:13 -0700 by sridhar golyandla