Canvas development manual full version

If there is no prompt for canvas in vscode, you can add this  

/** @type {HTMLCanvasElement} */

const can = document.querySelector("#id名");

get canvas

//canvas  

<canvas width="600" height="400" id="c1_box"></canvas>

//获取画笔,上下文对象

var c1 = document.getElementById('c1_box')

Determine whether the current browser supports canvas

//判断是否有getContext

if (!c1.getContext){

    console.log("当前浏览器不支持canvas□请下戟最新的浏览器");

}

get brushes

var ctx = c1.getContext('2d')

draw rectangle

Filling type: fi11Rect(position x, position y, width, height)

//一体式写法

ctx.fillRect(100,100,200,200)

//拆开写法(beginPath和closePath可以完成路径的分段)

ctx.beginPath();// 路径开始

    ctx.rect(100,100,200,200)

    ctx.fill()

ctx.closePath();// 路径结束

Path type: strokeRect(X1, y1, rectangle height, rectangle height)

//一体式写法

ctx.strokeRect(100,100,200,100);

//拆开写法(beginPath和closePath可以完成路径的分段)

ctx.beginPath();// 路径开始

    ctx.rect(100,100,200,200)

    ctx.stroke()

ctx.closePath();// 路径结束

Clear type: clearRect(X1, y1, width, height)

//间隔函数清除

  var height = 0;

  var time = setInterval(() => {

    height++;

    if (height > c1.clientHeight) {

      clearInterval(time);

    }

    ctx.clearRect(0, 0, c1.clientWidth, value);

  }, 10);

draw arc

ctx.arc(circle x, circle y, radius, start angle, end angle, whether it is clockwise (the default is clockwise false, counterclockwise true))

  ctx.arc(200, 200, 50, 0, Math.PI);

  //ctx.fill() //填充

  ctx.stroke(); //路径

moving brush

moveTo(The moveTo() method moves the path to the specified point in the canvas without creating a line.)

//绘制笑脸示例

<script>

  /** @type {HTMLCanvasElement} */

  var c1 = document.getElementById("c1_box");

  var ctx = c1.getContext("2d");



  ctx.beginPath();

  //绘制圆

  ctx.arc(100, 100, 50, 0, Math.PI * 2, true);

  ctx.moveTo(130, 100);

  //绘制嘴巴

  ctx.arc(100, 100, 30, 0, Math.PI);

  ctx.moveTo(90, 80);

  //绘制左眼

  ctx.arc(80, 80, 10, 0, Math.PI, true);

  ctx.moveTo(130, 80);

  //绘制右眼

  ctx.arc(120, 80, 10, 0, Math.PI, true);

  ctx.stroke();

  ctx.closePath();

</script>

draw polyline

lineTo(x, y) draws a line from the current position to the specified x and y position

//绘制三角形

<script>

  /** @type {HTMLCanvasElement} */

  var c1 = document.getElementById("c1_box");

  var ctx = c1.getContext("2d");



  ctx.beginPath();

  ctx.moveTo(300, 200);

  ctx.lineTo(300, 300);

  ctx.lineTo(400, 300);

  ctx.lineTo(300, 200);

  ctx.stroke();

  ctx.closePath();

</script>

Creates an arc/curve between two tangents

arcTo(x1, y1, x2, y2, radius), using the angle formed by the current endpoint, endpoint 1 (x1, y1) and endpoint 2 (x2, y2)

 <script>

  /** @type {HTMLCanvasElement} */

  var c1 = document.getElementById("c1_box");

  var ctx = c1.getContext("2d");



  ctx.beginPath();

  ctx.moveTo(50, 50);

  ctx.lineTo(150, 50);

  ctx.arcTo(200, 50, 200, 100, 50);

  ctx.stroke();

  ctx.closePath();

</script>

Bezier Conic

quadraticCurveTo(cpx,cpy,x,y);

cpx: The x-coordinate of the Bezier control point. cpy: The y coordinate of the Bezier control point. x: The x coordinate of the end point. y: The y coordinate of the end point.

//气泡框绘制

<script>

  /** @type {HTMLCanvasElement} */

  var c1 = document.getElementById("c1_box");

  var ctx = c1.getContext("2d");



  ctx.beginPath();

  ctx.moveTo(300, 200);

  ctx.quadraticCurveTo(250, 200, 250, 100);

  ctx.quadraticCurveTo(250, 50, 350, 50);

  ctx.quadraticCurveTo(450, 50, 450, 100);

  ctx.quadraticCurveTo(450, 200, 350, 200);

  ctx.quadraticCurveTo(350, 300, 300, 300);

  ctx.quadraticCurveTo(350, 300, 300, 200);



  ctx.stroke();

  ctx.closePath();

</script>

Bezier cubic curve

bezierCurveTo(cp1x,cp1y,cp2x,cp2y,x,y);

cp1x The x-coordinate of the first Bézier control point. cp1y The y-coordinate of the first Bezier control point.

cp2x The x-coordinate of the second Bézier control point. cp2y The y coordinate of the second Bézier control point.

x The x-coordinate of the end point. y The y coordinate of the end point.

//三次曲线绘制爱心

<script>

  /** @type {HTMLCanvasElement} */

  var c1 = document.getElementById("c1_box");

  var ctx = c1.getContext("2d");



  ctx.beginPath();

  ctx.moveTo(300, 200);

  ctx.bezierCurveTo(380, 120, 430, 200, 300, 300);

  // ctx.moveTo(300, 200);

  // ctx.bezierCurveTo(220, 120, 170, 200, 300, 300);

  ctx.bezierCurveTo(170, 200, 220, 120, 300, 200);



  ctx.stroke();

  ctx.closePath();

</script>

Path2D object

Path2D() can use objects in recent versions of browsers to cache or record these drawing commands, allowing for fast playback of paths.

Mainly used to reuse the encapsulated canvas path

//path2d封装爱心路径

<script>

  /** @type {HTMLCanvasElement} */

  var c1 = document.getElementById("c1_box");

  var ctx = c1.getContext("2d");



  var heartPath = new Path2D();

  heartPath.moveTo(300, 200);

  heartPath.bezierCurveTo(380, 120, 430, 200, 300, 300);

  heartPath.bezierCurveTo(170, 200, 220, 120, 300, 200);

  ctx.stroke(heartPath);

</script>

use svg path

You can use the svg path to initialize the path on the canvas,. This might allow you to pass path data and reuse them in SVG and canvas .

//svg draws a square path. M refers to moving to the specified point, h refers to horizontal drawing (abbreviation of horizontal), v refers to vertical drawing (abbreviation of vertical)

<script>

  /** @type {HTMLCanvasElement} */

  var c1 = document.getElementById("c1_box");

  var ctx = c1.getContext("2d");



  var squrePath = new Path2D("M 10 10 h 100 v 100 h -100 z");

  ctx.stroke(squrePath);

</script>

Color Style Control

fillStyle Fill color setting, format support: fillStyle = "#FF00FF";fillStyle = "rgba(255,150,200,1)";fillStyle = "skyblue";

strokeStyle line color setting, the format is the same as above

globalAlpha global transparency

Examples are as follows:

<script>

  /** @type {HTMLCanvasElement} */

  var c1 = document.getElementById("c1_box");

  var ctx = c1.getContext("2d");

  ctx.globalAlpha = 0.2;



  ctx.beginPath();

  ctx.moveTo(50, 50);

  ctx.fillStyle = "#FF00FF";

  ctx.fillRect(200, 50, 200, 100);

  ctx.closePath();



  ctx.beginPath();

  ctx.moveTo(200, 200);

  ctx.lineTo(200, 300);

  ctx.lineTo(300, 300);

  ctx.lineTo(200, 200);

  ctx.strokeStyle = "rgba(255,150,200,1)";

  ctx.strokeStyle = "red";

  ctx.stroke();

  ctx.fillStyle = "skyblue";

  ctx.fill();

  ctx.closePath();

</script>

linear gradient

createLinearGradient(x0,y0,x1,y1);

x0 is the x coordinate of the gradient start point, y0 is the y coordinate of the gradient start point, x1 is the x coordinate of the gradient end point, and y1 is the y coordinate of the gradient end point

The addColorStop() method specifies the position and color in the gradient object.

addColorStop(stop,color);

stop A value between 0.0 and 1.0 representing the position in the gradient between the start and end.

color The CSS color value to display at the end position.

requestAnimationFrame()

The usage of window.requestAnimationFrame() is very similar to setTimeout(), except that there is no need to set the time interval

requestAnimationFrame() will execute a callback function regularly, this time is about 60 times/s

In other words, it is about 60 frames per second (why is it 60, because the refresh rate of mainstream LCD monitors is 60Hz)

//Pink refresh bar effect

<script>

  /** @type {HTMLCanvasElement} */

  var c1 = document.getElementById("c1_box");

  console.log(c1.getContext, "c1");

  var ctx = c1.getContext("2d");



  let index = 0;

  function render() {

    ctx.clearRect(0, 0, 600, 400);

    index += 0.01;

    if (index > 1) {

      index = 0;

    }

    ctx.beginPath();

    var linearGradient = ctx.createLinearGradient(150, 150, 350, 250);

    linearGradient.addColorStop(0, "red");

    linearGradient.addColorStop(index, "pink");

    linearGradient.addColorStop(1, "blue");

    ctx.fillStyle = linearGradient;

    ctx.fillRect(150, 150, 200, 100);

    ctx.closePath();

    requestAnimationFrame(render);

  }



  requestAnimationFrame(render);

</script>

 

radial gradient

createRadialGradient(x0,y0,r0,x1,y1,r1);

x0 The x-coordinate of the gradient's starting circle. y0 The y-coordinate of the gradient's starting circle. r0 Radius of the starting circle.

x1 The x-coordinate of the end circle of the gradient. y1 The y coordinate of the end circle of the gradient. r1 The radius of the ending circle.

//径向渐变绘制3D球

<script>

  /** @type {HTMLCanvasElement} */

  var c1 = document.getElementById("c1_box");

  console.log(c1.getContext, "c1");

  var ctx = c1.getContext("2d");



  let ballGradient = ctx.createRadialGradient(150, 150, 10, 200, 200, 100);

  ballGradient.addColorStop(0, "pink");

  ballGradient.addColorStop(1, "red");

  ctx.fillStyle = ballGradient;



  ctx.arc(200, 200, 100, 0, Math.PI * 2);

  ctx.fill();

</script>

conical gradient

createConicGradient(angle, position x, position y)

//圆锥渐变绘制示例

<script>

  /** @type {HTMLCanvasElement} */

  var c1 = document.getElementById("c1_box");

  var ctx = c1.getContext("2d");



  var coneGradient = ctx.createConicGradient(0, 300, 200);

  coneGradient.addColorStop(0, "red");

  coneGradient.addColorStop(0.5, "yellow");

  coneGradient.addColorStop(1, "blue");

  ctx.fillStyle = coneGradient;

  ctx.fillRect(0, 0, 600, 400);

</script>

pattern sample fill style

createPattern(image,"repeat|repeat-x|repeat-y|no-repeat");

image An image, canvas or video element specifying the mode to use. (It can be an image object or a canvas object)  

repeat is the default. The pattern repeats horizontally and vertically. repeat-x The pattern repeats only horizontally.

repeat-y The pattern repeats only vertically. no-repeat The pattern is displayed only once (no repetition).

//pattern图片填充

<script>

  /** @type {HTMLCanvasElement} */

  var c1 = document.getElementById("c1_box");

  var ctx = c1.getContext("2d");



  var moneyImg = new Image();

  moneyImg.src = "./imgs/money.png";



  moneyImg.onload = function () {

    var moneyPattern = ctx.createPattern(moneyImg, "repeat");

    ctx.fillStyle = moneyPattern;

    ctx.fillRect(0, 0, 600, 400);

  };

</script>

line setting

Line width: lineWidth=number; (number is the width of the current line in pixels)

Sets or returns the style of line caps at the end of a line: lineCap="butt|round|square"; (butt default, adds a flat edge to each end of a line. round adds a rounded line cap to each end of a line. square Add square wire caps to each end of the line.)

Set or return the type of corner when the two created lines meet: lineJoin="bevel|round|miter"; (bevel creates bevel corners. round creates round corners. miter defaults. creates sharp corners.)

Set or return the maximum miter length: miterLimit=number; (number is a positive number. Specifies the maximum miter length. If the miter length exceeds the value of miterLimit, the corners will be displayed as "bevel" type of lineJoin.)

<script>

  /** @type {HTMLCanvasElement} */

  var c1 = document.getElementById("c1_box");

  var ctx = c1.getContext("2d");



  ctx.moveTo(50, 50);

  ctx.lineTo(70, 100);

  ctx.lineTo(90, 50);

  ctx.lineTo(110, 100);

  ctx.lineTo(130, 50);



  ctx.lineWidth = 10;

  ctx.lineCap = "round";

  ctx.lineJoin = "bevel";

  ctx.miterLimit = 2;



  ctx.stroke();

</script>

dotted line style

setLineDash(segments);(segments An array. A set of numbers describing the length of alternately drawn line segments and spacing (coordinate space units)

If the number of elements in the passed segments array is odd, the elements of the array will be copied and repeated. For example, [5, 15, 25] will become [5, 15, 25, 5, 15, 25])

Set the dashed line offset: lineDashOffset = value; (the value offset is a number with float precision. The initial value is 0.0.)

<script>

  /** @type {HTMLCanvasElement} */

  var c1 = document.getElementById("c1_box");

  var ctx = c1.getContext("2d");

  let index = 0;

  var render = function () {

    ctx.clearRect(0, 0, 600, 400);

    if (index > 400) {

      index = 0;

    }

    index += 1;

    ctx.moveTo(50, 50);

    ctx.lineTo(100, 100);

    ctx.lineTo(150, 50);

    ctx.lineTo(200, 100);

    ctx.lineTo(250, 50);



    ctx.lineWidth = 1;

    ctx.setLineDash([10, 5]);

    ctx.lineDashOffset = index;



    ctx.stroke();

    requestAnimationFrame(render);

  };

  requestAnimationFrame(render);

</script>

shadow

shadowColor sets or returns the color used for shadows.

shadowBlur sets or returns the blur level of the shadow.

shadowOffsetX Sets or returns the horizontal distance from the shadow to the shape.

shadowOffsetY Sets or returns the vertical distance from the shadow to the shape.

<script>

  /** @type {HTMLCanvasElement} */

  var c1 = document.getElementById("c1_box");

  var ctx = c1.getContext("2d");



  ctx.beginPath();

  ctx.moveTo(300, 200);

  ctx.bezierCurveTo(380, 120, 430, 200, 300, 300);

  ctx.bezierCurveTo(170, 200, 220, 120, 300, 200);

  ctx.shadowOffsetX = 5;

  ctx.shadowOffsetY = 5;

  ctx.shadowColor = "red";

  ctx.shadowBlur = 5;



  ctx.stroke();

  ctx.closePath();

</script>

Three modes of drawing pictures

The first way to draw pictures, parameter 1 is the picture object, parameter 2 is to dye the picture to the horizontal position of the canvas, and parameter 3 is to dye the picture to the vertical position of the canvas:

ctx.drawImage(img,0,0);

The second way to draw a picture, parameter 1 is the picture object, parameter 2 is to dye the picture to the horizontal position of the canvas, parameter 3 is to dye the picture to the vertical position of the canvas, parameter 4 is to scale the picture to the corresponding width, and parameter 5 will be The image is scaled to

ctx.drawImage(img,0,0,600,400);

The third way to draw a picture, the four parameters after the mg parameter are the starting point of the pixel you want to crop on the source picture and the width and height of the rectangle, and the last four parameters are the position of the canvas and the width and height of the rectangle to be rendered.

ctx.drawImage(img, 122, 225, 225, 225, 0, 0, 600, 400);

<script>

  /** @type {HTMLCanvasElement} */

  var c1 = document.getElementById("c1_box");

  var ctx = c1.getContext("2d");



  var dogImg = new Image();

  dogImg.src = "./imgs/dog.jpeg";

  dogImg.onload = function () {

    ctx.drawImage(dogImg, 122, 225, 225, 225, 0, 0, 600, 400);

  };

</script>

 

 Draw dynamic video and add watermark

<script>

  /** @type {HTMLCanvasElement} */

  var c1 = document.getElementById("c1_box");

  var ctx = c1.getContext("2d");



  var cat_video = document.createElement("video");

  cat_video.src = "./imgs/cat.mp4";



  var btn = document.querySelector("#btn");

  btn.addEventListener("click", () => {

    if (cat_video.paused) {

      cat_video.play();

      render();

    } else {

      cat_video.pause();

    }

  });



  let image = new Image();

  image.src = "./imgs/baidu_logo.png";

  function render() {

    ctx.clearRect(0, 0, 600, 400);

    ctx.drawImage(cat_video, 0, 0, 600, 400);

    ctx.drawImage(image, 400, 350, 200, 50);

    requestAnimationFrame(render);

  }

</script>

draw text

text size, font

 ctx.font = "48px serif";

fill rendered text

fillText(text,x,y,maxWidth);

text specifies the text to output on the canvas.

x The x-coordinate position (relative to the canvas) at which to start drawing the text. y The y-coordinate position (relative to the canvas) at which to start drawing the text.

maxWidth is optional. The maximum text width allowed, in pixels.

ctx.fillText("Hello Canvas", 300, 200, 100);

 strokeText(text,x,y,maxWidth);

ditto

text alignment

textAlign="center|end|left|right|start";

The textAlign property sets or returns the current alignment of the text content, based on the anchor point.

baseline alignment

textBaseline="alphabetic|top|hanging|middle|ideographic|bottom";

The textBaseline property sets or returns the current text baseline when drawing text. Default alphabetic.

Premeasured text width

When you need to get more text details, the following method can give you a way to measure the text.

measureText()

It will return the width and pixels of a TextMetrics object, which reflect the properties of the text.

The following code snippet will show how to measure text to get its width:

function draw() {

  var ctx = document.getElementById('canvas').getContext('2d');

  var text = ctx.measureText("foo"); // TextMetrics object

  text.width; // 16;

}

Displacement, scaling, rotation transformation

move translate(x, y)

The translate method shifts the coordinate system and accepts two parameters. *x * is the left and right offset, y is the up and down offset

Zoom scale(x, y)

The scale method can scale the horizontal and vertical units of the canvas (stretching the coordinate system). Both parameters are real numbers, can be negative, x is the horizontal scaling factor, y is the vertical scaling factor

rotate rotate(angle)

This method accepts only one parameter: the angle of rotation (angle), which is a clockwise value in radians.

The center point of the rotation is always the origin of the canvas, if we want to change it, we need to use the translate method.

Matrix transform transformation (understand)

transform(a, b, c, d, e, f)

This method is to multiply the current deformation matrix by a matrix based on its own parameters, as shown in the following matrix:

 The parameters of this function represent the following:

a (m11) scaling in the horizontal direction

b(m12) tilt offset in the vertical direction

c(m21) tilt offset in horizontal direction

d(m22) scaling in the vertical direction

e(dx) horizontal movement

f(dy) vertical movement

//以下代码代表坐标系不变,位移x100,y200

transform(1, 0, 0, 1, 100, 200);

composite image

globalCompositeOperation="source-over";

The globalCompositeOperation property sets or returns how a source (new) image is drawn onto the destination (existing) image.

Source image = the drawing you intend to place on the canvas.

Target image = the drawing you've placed on the canvas.

attribute value

value

describe

source-over

default. Displays the source image over the destination image.

source-atop

Displays the source image on top of the destination image. Portions of the source image outside the destination image are not visible.

source-in

Display the source image in the destination image. Only the portion of the source image that is within the destination image is displayed, and the destination image is transparent.

source-out

Displays the source image outside of the destination image. Only the portion of the source image that is outside the destination image is displayed, and the destination image is transparent.

destination-over

Displays the destination image over the source image.

destination-atop

Displays the destination image on top of the source image. Portions of the destination image outside the source image are not visible.

destination-in

Display the target image in the source image. Only the part of the destination image inside the source image will be displayed, the source image is transparent.

destination-out

Displays the destination image outside of the source image. Only the portion of the destination image outside the source image will be displayed, the source image is transparent.

lighter

Show source image + destination image.

copy

Display the source image. Target image is ignored.

xor

Combine the source and destination images using an XOR operation.

//刮刮卡源码

<!DOCTYPE html>

<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>Document</title>

    <style>

      canvas {

        border: 1px solid #ccc;

        position: absolute;

        z-index: 10;

      }

      .reward {

        width: 600px;

        height: 400px;

        position: absolute;

        text-align: center;

        line-height: 400px;

        font-size: 30px;

        font-weight: 700;

      }

    </style>

  </head>

  <body>

    <div class="reward" id="reward">谢谢惠顾!</div>

    <canvas width="600" height="400" id="c1_box"></canvas>

  </body>

</html>

<script>

  /** @type {HTMLCanvasElement} */

  var c1 = document.getElementById("c1_box");

  var ctx = c1.getContext("2d");



  var img_bg = new Image();

  img_bg.src = "./imgs/zzc.jpeg";



  img_bg.onload = () => {

    ctx.drawImage(img_bg, 0, 0, 600, 400);

  };



  var isClean = false;

  c1.onmousedown = () => {

    isClean = true;

  };

  c1.onmouseup = () => {

    isClean = false;

  };

  c1.onmousemove = (e) => {

    ctx.beginPath();

    if (isClean) {

      var x = e.pageX;

      var y = e.pageY;

      ctx.globalCompositeOperation = "destination-out";

      ctx.arc(x, y, 20, 0, Math.PI * 2);

      ctx.fill();

    }

    ctx.closePath();

  };



  var random_number = Math.random();

  if (random_number < 0.1) {

    document.querySelector("#reward").innerHTML =

      "恭喜你获得一台IPONRE PRO 14大奖";

  }

</script>

cut out

The clip() method clips an arbitrary shape and size from the original canvas.

Tip: Once an area is clipped, all subsequent drawing will be restricted to the clipped area (no access to other areas on the canvas). You can also save the current canvas area by using the save() method before using the clip() method, and restore it at any later time (via the restore() method).

//裁剪爱心区域

<script>

  /** @type {HTMLCanvasElement} */

  var c1 = document.getElementById("c1_box");

  var ctx = c1.getContext("2d");



  var heartPath = new Path2D();

  heartPath.moveTo(300, 200);

  heartPath.bezierCurveTo(380, 120, 430, 200, 300, 300);

  heartPath.bezierCurveTo(170, 200, 220, 120, 300, 200);

  ctx.clip(heartPath);



  var img = new Image();

  img.src = "./imgs/dog.jpeg";

  img.onload = () => {

    ctx.drawImage(img, 0, 0, 600, 400);

  };

</script>

State saving and restoration

save(): Used to save the state of the Canvas. After saving, you can call Canvas's translation, scaling, rotation, miscutting, cropping and other operations.

restore(): Used to restore the previously saved state of Canvas. Prevent operations performed on Canvas after save from affecting subsequent drawing. blog

Save and restore should be used in pairs (restore can be less than save, but not more). If the number of restore calls is more than save, an Error will be caused. (first in last out)

<script>

  /** @type {HTMLCanvasElement} */

  var c1 = document.getElementById("c1_box");

  console.log(c1.getContext, "c1");

  var ctx = c1.getContext("2d");



  ctx.fillStyle = "red";

  ctx.fillRect(0, 0, 100, 100);

  ctx.save();



  ctx.fillStyle = "blue";

  ctx.fillRect(100, 100, 100, 100);

  ctx.save();



  ctx.fillStyle = "yellow";

  ctx.fillRect(200, 200, 100, 100);

  ctx.save();



  ctx.restore();

  ctx.fillRect(300, 300, 100, 100);



  ctx.restore();

  ctx.fillRect(400, 400, 100, 100);



  ctx.restore();

  ctx.fillRect(500, 500, 100, 100);

</script>

 pixel manipulation

The getImageData() method returns an ImageData object that copies the pixel data of the specified rectangle of the canvas.

For each pixel in the ImageData object, there are four aspects of information, namely the RGBA value:

R - red (0-255)
G - green (0-255)
B - blue (0-255)
A - alpha channel (0-255; 0 is transparent, 255 is fully visible)

The color/alpha information exists in the form of an array (4 in a group), and is stored in the data property of the ImageData object.

getImageData(x,y,width,height);

x The x-coordinate, in pixels, of the upper-left corner location to start copying.

y The y-coordinate, in pixels, of the upper-left corner location to start copying.

width The width of the rectangular area to copy.

height The height of the rectangular area to copy.

putImageData(imgData,x,y,dirtyX,dirtyY,dirtyWidth,dirtyHeight);

The putImageData() method puts image data (from the specified ImageData object) back on the canvas.

imgData specifies the ImageData object to put back on the canvas.

x The x-coordinate of the upper left corner of the ImageData object, in pixels.

y The y-coordinate of the upper-left corner of the ImageData object, in pixels.

dirtyX Optional. Horizontal value (x), in pixels, where to place the image on the canvas.

dirtyY Optional. Horizontal value (y), in pixels, where to place the image on the canvas.

dirtyWidth is optional. The width used to draw the image on the canvas.

dirtyHeightOptional. The height used to draw the image on the canvas.

<script>

  /** @type {HTMLCanvasElement} */

  var c1 = document.getElementById("c1_box");

  var ctx = c1.getContext("2d");



  var dogImg = new Image();

  dogImg.src = "./imgs/dog.jpeg";

  dogImg.onload = function () {

    ctx.drawImage(dogImg, 122, 225, 225, 225, 0, 0, 600, 400);



    let imageData = ctx.getImageData(0, 0, 600, 400);

    for (var i = 0; i < imageData.data.length; i += 4) {

      var avg =

        (imageData.data[i] + imageData.data[i + 1] + imageData.data[i + 2]) / 3;



      imageData.data[i] = avg;

      imageData.data[i + 1] = avg;

      imageData.data[i + 2] = avg;

      imageData.data[i + 3] = 255;

    }

    // ctx.putImageData(imageData, 0, 0);

    ctx.putImageData(imageData, 0, 0, 300, 200, 300, 200);

  };

</script>

 Advanced Package Drawing Elements

isPointInPath(x,y); If the specified point is in the current path, the isPointInPath() method returns true, otherwise returns false.

x The x coordinate to test.

y The y coordinate to test.

<script>

  /** @type {HTMLCanvasElement} */

  var c1 = document.getElementById("c1_box");

  var ctx = c1.getContext("2d");



  class Heart {

    constructor(x, y) {

      this.x = x;

      this.y = y;

      this.color = "red";

      this.heartPath = new Path2D();

      this.heartPath.moveTo(this.x, this.y);

      this.heartPath.bezierCurveTo(

        this.x + 80,

        this.y - 80,

        this.x + 130,

        this.y,

        this.x,

        this.y + 100

      );

      this.heartPath.bezierCurveTo(

        this.x - 130,

        this.y,

        this.x - 80,

        this.y - 80,

        this.x,

        this.y

      );



      c1.onmousemove = (e) => {

        let x = e.pageX;

        let y = e.pageY;

        let isIn = ctx.isPointInPath(this.heartPath, x, y);

        if (isIn) {

          this.color = "blue";

        } else {

          this.color = "red";

        }

      };

    }



    draw() {

      ctx.save();

      ctx.fillStyle = this.color;

      ctx.fill(this.heartPath);

      ctx.restore();

    }

  }



  const heart = new Heart(300, 200);



  function render() {

    ctx.clearRect(0, 0, c1.offsetWidth, c1.offsetHeight);



    heart.draw();

    requestAnimationFrame(render);

  }

  render();

</script>

Canvas object is converted to base64 bit encoding

toDataURL(type, encoderOptions), convert the canvas object to base64 encoding

type specifies the format of the image converted to base64 encoding, such as: image/png, image/jpeg, image/webp, etc., and the default is image/png format;

encoderOptions is used to set the quality of the image converted to base64 encoding, the value range is 0-1, and the default value 0.92 is replaced if the value exceeds the value range;

//画板案例

<!DOCTYPE html>

<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>Document</title>

    <style>

      canvas {

        border: 1px solid #000;

      }



      .button_active {

        background-color: skyblue;

      }

    </style>

  </head>

  <body>

    <canvas width="1400" height="600" id="c1_box"></canvas>

    <hr />

    <button id="boldLine">粗线条</button>

    <button id="thinLine">细线条</button>

    <button id="save">保存签名</button>

    <input type="color" id="color" />

    <button id="rubber">橡皮擦</button>

    <button id="none">清空画布</button>

  </body>

</html>

<script>

  /** @type {HTMLCanvasElement} */

  var c1 = document.getElementById("c1_box");

  var ctx = c1.getContext("2d");

  ctx.lineJoin = "round";

  //是否作画

  var isDraw = false;

  // 获取元素

  let boldLine = document.querySelector("#boldLine");

  let thinLine = document.querySelector("#thinLine");

  let save = document.querySelector("#save");

  let color = document.querySelector("#color");

  let rubber = document.querySelector("#rubber");

  let none = document.querySelector("#none");



  c1.onmousedown = (e) => {

    ctx.beginPath();

    isDraw = true;

    let x = e.pageX - c1.offsetLeft;

    let y = e.pageY - c1.offsetTop;

    ctx.moveTo(x, y);

  };



  c1.onmousemove = (e) => {

    if (isDraw) {

      let x = e.pageX - c1.offsetLeft;

      let y = e.pageY - c1.offsetTop;

      ctx.lineTo(x, y);

      ctx.stroke();

    }

  };



  c1.onmouseleave = (e) => {

    isDraw = false;

    ctx.closePath();

  };



  c1.onmouseup = (e) => {

    isDraw = false;

    ctx.closePath();

  };



  boldLine.onclick = () => {

    ctx.globalCompositeOperation = "source-over";

    boldLine.classList.add("button_active");

    thinLine.classList.remove("button_active");

    rubber.classList.remove("button_active");

    ctx.lineWidth = 20;

  };

  thinLine.onclick = () => {

    ctx.globalCompositeOperation = "source-over";

    thinLine.classList.add("button_active");

    boldLine.classList.remove("button_active");

    rubber.classList.remove("button_active");

    ctx.lineWidth = 2;

  };



  rubber.onclick = () => {

    rubber.classList.add("button_active");

    thinLine.classList.remove("button_active");

    boldLine.classList.remove("button_active");

    ctx.lineWidth = 30;

    ctx.globalCompositeOperation = "destination-out";

  };



  none.onclick = () => {

    ctx.clearRect(0, 0, c1.width, c1.height);

  };



  color.onchange = () => {

    ctx.strokeStyle = color.value;

  };



  save.onclick = () => {

    const downHref = c1.toDataURL();

    let download_a = document.createElement("a");

    download_a.setAttribute("download", "个性签名");

    download_a.href = downHref;

    download_a.click();

  };

</script>

case clock

<!DOCTYPE html>

<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>Document</title>

    <style>

      canvas {

        border: 1px solid #ccc;

      }

    </style>

  </head>

  <body>

    <canvas width="800" height="600" id="c1_box"></canvas>

  </body>

</html>

<script>

  /** @type {HTMLCanvasElement} */

  var c1 = document.getElementById("c1_box");

  var ctx = c1.getContext("2d");

  function render() {

    ctx.clearRect(0, 0, c1.width, c1.height);

    ctx.save();

    ctx.translate(400, 300);

    ctx.rotate(-Math.PI / 2);

    ctx.save();

    for (var i = 0; i < 12; i++) {

      ctx.beginPath();

      ctx.moveTo(170, 0);

      ctx.lineTo(190, 0);

      ctx.lineWidth = 8;

      ctx.strokeStyle = "gray";

      ctx.stroke();

      ctx.closePath();

      ctx.rotate((Math.PI * 2) / 12);

    }

    ctx.restore();

    ctx.save();



    for (var i = 0; i < 60; i++) {

      ctx.beginPath();

      ctx.moveTo(180, 0);

      ctx.lineTo(190, 0);

      ctx.lineWidth = 2;

      ctx.strokeStyle = "gray";

      ctx.stroke();

      ctx.closePath();

      ctx.rotate((Math.PI * 2) / 60);

    }

    ctx.restore();

    ctx.save();



    var time = new Date();

    var hour = time.getHours();

    var min = time.getMinutes();

    var sec = time.getSeconds();

    hour = hour > 12 ? hour - 12 : hour;



    //秒针

    ctx.rotate(((Math.PI * 2) / 60) * sec);

    ctx.beginPath();

    ctx.moveTo(180, 0);

    ctx.lineTo(-30, 0);

    ctx.lineWidth = 2;

    ctx.strokeStyle = "red";

    ctx.stroke();

    ctx.closePath();

    ctx.restore();

    ctx.save();



    //分针

    ctx.rotate(((Math.PI * 2) / 60) * min + ((Math.PI * 2) / 60 / 60) * sec);

    ctx.beginPath();

    ctx.moveTo(150, 0);

    ctx.lineTo(-30, 0);

    ctx.lineWidth = 2;

    ctx.strokeStyle = "#888";

    ctx.stroke();

    ctx.closePath();

    ctx.restore();



    //时针

    ctx.rotate(

      ((Math.PI * 2) / 12) * hour +

        ((Math.PI * 2) / 12 / 60) * min +

        ((Math.PI * 2) / 60 / 60) * sec

    );

    ctx.beginPath();

    ctx.moveTo(100, 0);

    ctx.lineTo(-30, 0);

    ctx.lineWidth = 5;

    ctx.strokeStyle = "#000";

    ctx.stroke();

    ctx.closePath();

    ctx.restore();

    requestAnimationFrame(render);

  }

  render();

</script>

Guess you like

Origin blog.csdn.net/yxlyttyxlytt/article/details/130397886