canvas

www.w3school.com.cn/tags/html_r…

The canvas element

< Canvas > is a new addition to HTML5, an HTML element that can be used to draw images using scripts (usually JavaScript). It can be used to create photo collections or simple (and not so simple) animations, or even real-time video processing and rendering.


looks just like the
tag except that

has two optional properties: width and heigth, and no SRC or Alt properties.

If you do not set the widHT and height properties for the

, the default width is 300 and the height is 150, in units of px. You can also use the CSS property to set the width and height, but if the width and height property is not consistent with the initial ratio, it will be distorted. Therefore, it is recommended that you never use CSS properties to set the width and height of the < Canvas >.

Thre Rending Context

The Canvas element creates a fixed-size canvas that exposes one or more rendering contexts that can be used to draw and process the content to be displayed. We will focus our attention on the 2D rendering context. The element has a method called getContext(), which is used to get the render context and its drawing function.

var canvas = document.getElementById('tutorial'); Var CTX = Canvas. GetContext ('2d');Copy the code

Draw a rectangle

Unlike SVG, only two forms of graphic drawing are supported: rectangles and paths (line segments connected by a series of points). All other types of graphs are composed by a combination of one or more paths.

Canvas provides three ways to draw a rectangle:

  • FillRect (x, y, width, height) draws a filled rectangle that is filled in black by default
  • StrokeRect (x, y, Width, height) draws a rectangular border
  • ClearRect (x, y, width, height) Clears the specified rectangular area, making the cleared part completely transparent.

X and y specify the coordinates of the upper-left corner (relative to the origin) of the rectangle to be drawn on the canvas. Width and height set the size of the rectangle.

Draw the path

The basic element of a graph is the path. A path is a collection of points of different shapes connected by line segments or curves of different colors and widths. A path, even a subpath, is closed.

  1. First, you need to create the starting point of the path.
  2. Then you use the draw command to draw the path.
  3. And then you close the path.
  4. Once the path is generated, you can render the figure by stroke or by filling the path area.
  • beginPath()

    · Create a new path. After the path is generated, the graph drawing command is pointed to the path to generate the path

  • closePath()

    After closing the path, the graph drawing command points back to the context.

  • moveTo(x,y)

    Method moves the path to a specified point on the canvas without creating a line.

  • stroke()

    To draw the outline of a figure by using lines

  • lineTo(x,y)

    Draws a line from the current position to the specified x and y positions.

  • fill()

    Generate a solid graph by filling the content area of the path.

Note: When you call fill(), all shapes that are not closed automatically close, so you don’t need to call closePath(). But the stroke() call does not automatically close * *.

Draw a triangle

For example, the code for drawing a triangle looks like this:

function draw() { var canvas = document.getElementById('canvas'); if (canvas.getContext) { var ctx = canvas.getContext('2d'); ctx.beginPath(); ctx.moveTo(75, 50); ctx.lineTo(100, 75); ctx.lineTo(100, 25); ctx.fill(); }}Copy the code

Styles and colors

Color rendering

  • FillStyle = color Sets the fill color of the graph.
  • StrokeStyle = color Sets the color of the shape outline.

Once you set the strokeStyle or fillStyle value, this new value becomes the default value for the newly drawn graph. If you want to give each figure a different color, you need to reset the fillStyle or strokeStyle values.

  • The Transparency of Transparency

    In addition to drawing solid colors, we can also use Canvas to draw translucent shapes. By setting the globalAlpha property or using a translucent color as a style for the contour or fill.

    • globalAlpha = transparencyValue

      This property affects the opacity of all drawings on the Canvas. The valid value ranges from 0.0 (fully transparent) to 1.0 (fully opaque). The default is 1.0.

Linear Line styles

  • LineWidth = value sets the lineWidth.
  • LineCap = type Sets the line end style.
  • LineJoin = type Sets the style of lines and line injunctions.
  • MiterLimit = value Limits the maximum length at the junction when two lines intersect; The length of the so-called junction (miter length) is the length from the vertex of the inner Angle to the vertex of the outer Angle at the junction of the lines.
  • GetLineDash () returns an array containing the current dashed line style with a non-negative even length.
  • SetLineDash (segments) Sets the current dashed line style.
  • LineDashOffset = value Sets the starting offset for the dotted line style.

The gradient Gradients

Just like any other drawing software, we can use linear or radial gradients to fill or stroke edges. Create a New canvasGradient object and assign it to the fillStyle or strokeStyle property of the graph using the following method.

  • The createLinearGradient method takes four parameters, representing the starting point (x1,y1) and the end point (x2,y2) of the gradient.
  • The createRadialGradient method accepts six parameters. The first three define a circle with the origin (x1,y1) and radius r1, The last three parameters define another circle of radius R2 with the origin (x2,y2).
Var that lineargradient = CTX. CreateLinearGradient,0,150,150 (0); Var radialgradient = CTX. CreateRadialGradient,75,0,75,75,100 (75);Copy the code

Copy to Clipboard

Once we have created the canvasGradient object, we can use the addColorStop method to color it.

  • gradient.addColorStop(position, color)

    The addColorStop method takes two arguments. The position argument must be a number between 0.0 and 1.0, indicating the relative position of the color in the gradient. For example, 0.5 means the color will appear right in the middle. The color parameter must be a valid CSS color value (such as #FFF, rgba(0,0,0,1), etc.).

The Patterns of the Patterns

In the example in the last video, I used a loop to create a pattern. In fact, there is an even simpler way: createPattern.

CreatePattern (Image, type) This method takes two arguments. Image can be a reference to an Image object, or another Canvas object. Type must be one of the following string values: repeat, repeat-x, repeat-y, and no-repeat. Note: Using the Canvas object as the Image parameter is not valid in Firefox 1.5 (Gecko 1.8). A pattern is applied much like a gradient. Once a pattern is created, assign it to fillStyle or strokeStyle.

var img = new Image(); img.src = ‘someimage.png’; var ptrn = ctx.createPattern(img,’repeat’);

Shadow we

  • ShadowOffsetX = float shadowOffsetX and shadowOffsetY are used to set the extension distance of the shadow on the X and Y axis. They are not affected by the transformation matrix. A negative value means the shadow will extend up or to the left, and a positive value means it will extend down or to the right, both of which default to 0.
  • ShadowOffsetY = float shadowOffsetX and shadowOffsetY are used to set the extension distance of the shadow on the X and Y axis, which are not affected by the transformation matrix. A negative value means the shadow will extend up or to the left, and a positive value means it will extend down or to the right, both of which default to 0.
  • ShadowBlur = float shadowBlur is used to set the blur of the shadow. The value is not linked to the number of pixels and is not affected by the transformation matrix. The default value is 0.
  • ShadowColor is a standard CSS color used to set the shadowColor effect. The default is a transparent black color

image

Upload the image

<input type="file"></input>
Copy the code
function getObjectURL(file) { var url = null; if (window.createObjcectURL ! = undefined) { url = window.createOjcectURL(file); } else if (window.URL ! = undefined) { url = window.URL.createObjectURL(file); } else if (window.webkitURL ! = undefined) { url = window.webkitURL.createObjectURL(file); } return url; } var objURL = getObjectURL(imgFile); / / object / / objURL imgFile file - > blob: / / http://127.0.0.1:5500/d17cdcc3-b698-4011-a6d2-f63360cdd22b you can use it like using normal URL, For example, img.src. $("#img").attr("src", objURL);Copy the code

Through the window. The URL. CreateObjectURL method can turn a blob into a blob URL, and used as a file download links or pictures showed. A File object is a special type of Blob object

Every time you call window. URL. CreateObjectURL (), creates a unique object URL, even if you to a URL has created the object files to create an object URL again. Each created object URL must be released. When the documents are closed, they are automatically released. If your website is to use them dynamically, you need to explicitly call window. The URL. RevokeObjectURL () to release them

Draw pictures

How to get the picture

  • The HTMLImageElement Image is constructed by the Image() function, or whatever it isThe element

    • Use the script to create a new HTMLImageElement object using the Image() constructor

      var img = new Image(); // Create a <img> element img.src = objURL; // Set the image source addressCopy the code

      If the image is not loaded when drawImage is called, nothing happens (some older browsers may throw an exception). So you should use the load event to make sure you don’t use the image until it’s loaded:

      Var img = new Image(); // Create the img element img.src = 'myimage.png '; Img. Onload = function(){// Execute the drawImage statement //1. Ctx. drawImage(this,offsetX,0,imgW,imgH); DrawImage (document.getelementByid ("img"), 0, 0, imgW, imgH); }Copy the code
  • HTMLVideoElement uses an HTML element as your image source, capturing the current frame from the video as an image

  • HTMLCanvasElement can use another element as your image source.

    • HTMLCanvasElement. ToDataURL () to obtain corresponding data – canvas URL (a Base64 encoded string).

      canvas.toDataURL(type, encoderOptions); Type The optional default format type is image/png. encoderOptions An optional representation of the image quality that uses lossy compression for the image formats used, such as image/ JPEG and Image /webp. If this parameter is any other parameter, the default value for image quality is used. The default value is 0.92Copy the code
      var canvas = document.getElementById("canvas"); var dataURL = canvas.toDataURL(); SRC = dataURL // SRC -> //'data:image/ GIF; base64,R0lGODlhCwALAIAAAAAA3pn/ZiH5BAEAAAEALAAAAAALAAsAAAIUhA+hkcuO4lmNVindo7qyrIXiGBYAOw==';Copy the code

      Set jPEGS image quality

      Var fullQuality = Canvas. ToDataURL ("image/jpeg", 1.0); // data:image/jpeg; base64,/9j/4AAQSkZJRgABAQ... 9 oadambaairaxeapwd/AD / 6 ap/Z "var mediumQuality = canvas. ToDataURL (" image/jpeg", 0.5); Var lowQuality = Canvas. ToDataURL ("image/jpeg", 0.1);Copy the code
  • ImageBitmap is a high-performance bitmap that can be drawn with low latency and can be generated from all of the above sources as well as several others.

clipboard

  • Clipboard.js: Selection and execCommand API

    Run clipboardjs.issupported () to check whether clipboard.js isSupported

    Click the button twice before executing

    Juejin. Cn/post / 690663…

  • Images are written to the clipboard

    Juejin. Cn/post / 690923…

  • Base64,file and Blob conversion

    Juejin. Cn/post / 684490…

  • Ruan Yifeng: Clipboard API tutorial

    www.ruanyifeng.com/blog/2021/0…

The text

<input id="foo" type="text" value=" <button class=" BTN "data-clipboard-action="copy" data-clipboard-target="#foo"> </button> <script> var clipboard  = new ClipboardJS('.btn'); clipboard.on('success', function(e) { console.log(e); }); clipboard.on('error', function(e) { console.log(e); }); </script>Copy the code

In addition to the input element, the target of replication can also be a div or textarea element. In the example above, the target of our replication is specified by the data-* attribute. In addition, we can also set the target of the copy when we instantiate clipBoard:

// https://github.com/zenorocha/clipboard.js/blob/master/demo/function-target.html let clipboard = new ClipboardJS('.btn', { target: function() { return document.querySelector('div'); }}); Copy the codeCopy the code

If we need to set the copied text, we can also set the copied text when we instantiate the ClipBoard object:

// https://github.com/zenorocha/clipboard.js/blob/master/demo/function-text.html let clipboard = new ClipboardJS('.btn', {text: function() {return 'Hello, I'm Bog '; }});Copy the code

image

/ / converts base64 blob object / / https://juejin.cn/post/6844903862873112583 function dataURLtoFile (dataurl, filename) { var arr = dataurl.split(","); var mime = arr[0].match(/:(.*?) ; / [1]); var bstr = atob(arr[1]); var n = bstr.length; var u8arr = new Uint8Array(n); while (n--) { u8arr[n] = bstr.charCodeAt(n); } //return new file ([u8arr], filename, {type: mime}); Return new blob ([u8arr], {type: mime}); } var imageBlob = dataURLtoFile(src); const item = new ClipboardItem({ [imageBlob.type]: imageBlob, }); // Check whether the browser supports clipboard-write Async function askWritePermission() {try {const {state} = await navigator.permissions.query({ name: "clipboard-write", }); return state === "granted"; } catch (error) { return false; } } if (askWritePermission()) { navigator.clipboard.write([item]); Alert (" Copy to clipboard successfully "); } else {alert(" copy not supported "); }Copy the code

Chrome dictates that navigator. Clipboard only uses the API for HTTPS pages. However, the development environment (localhost) Allows the use of non-encryption protocols.

A blob object

Developer.mozilla.org/zh-CN/docs/…

zhuanlan.zhihu.com/p/97768916

The Blob object represents an immutable, raw data – like file object. Its data can be read in either text or binary format

As you can see, the myBlob object has two properties: size and Type. The size attribute is used to indicate the size of the data in bytes, and type is a string of MIME types. A Blob does not necessarily represent data in a JavaScript native format. The File interface, for example, is based on the Blob, inheriting the functionality of the Blob and extending it to support files on the user’s system.

A Blob consists of an optional string type (usually MIME type) and blobParts:

The syntax for the Blob constructor is:

var aBlob = new Blob(blobParts, options);
Copy the code

BlobParts: This is an array of objects consisting of ArrayBuffer, ArrayBufferView, Blob, DOMString, etc. DOMStrings will be encoded as UTF-8.

Options: An optional object containing the following two properties:

  • Type — The default is""Which represents the MIME type of the array contents to be put into the BLOB.
  • The default is “endings”"transparent", which specifies to include a line terminator\nHow the string is written to. It is one of two values:"native", which means the line terminator will be changed to a newline suitable for the host operating system file system, or"transparent", which means that the ending character saved in the BLOB is kept unchanged.

The file object

Developer.mozilla.org/zh-CN/docs/…

A File object is a FileList object returned from a user who selects a File on an element. It can also be a DataTransfer object generated by drag-and-drop operations

A File object is a special type of Blob and can be used in any Blob type context

ImageData object

The ImageData object holds the real pixel data of the Canvas object

getImageData(left, top, width, height)

Gets an ImageData image containing the pixel data of the canvas scene

  • **width** Image width, in pixels

  • Height The height of the image, in pixels

  • data

    Uint8ClampedArray one-dimensional array containing integer data in RGBA format ranging from 0 to 255 inclusive

PutImageData () writes pixel data to the scene

Image fuzzy

Developer.mozilla.org/zh-CN/docs/…

zhuanlan.zhihu.com/p/31426945

Juejin. Cn/post / 684490…

Device pixel ratio

DevicePixelRatio (window.devicepixelratio) of the current display devicePhysical pixelResolution andCSS pixelResolution ratio, this value can also be interpreted as the ratio of pixel sizes: the size of a CSS pixel to the size of a physical pixel. In simple terms, it tells the browser how many actual screen pixels to use to draw individual CSS pixels.

Back in the old days before high score screens, a develop-written 1 pixel was actually 1 pixel (if you didn’t consider scaling), and you didn’t have to do anything special. If the CSS is set to 100px, it is 100px.

Then came the phone with the high score screen, and the mysterious devicePixelRatio property appeared under the Window object, and could be used to judge the device epixelratio in media queries. This property means the ratio of CSS pixels (logical pixels) to actual pixels (physical pixels) at rendering time. For example, the iPhone 4S has a value of 2 in its devicePixelRatio attribute, which is 100px logical pixels equal to 200px of the device’s actual pixels. Points that used to be drawn with one pixel are now drawn with two pixels.

Canvas’s CSS width, height andThe canvas wide high

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

The width and height properties of the Canvas tag are not the WIDTH and height of the CSS, but the canvas width and height (drawing area). When the CSS width and height of the canvas are not set, The Canvas will use the width and height values as the CSS width height, which is the visible size of the element on the page

However, the context width and height of the canvas is a little strange. It doesn’t matter whether the pixel ratio is 1, 2 or 3, it just fills the entire canvas drawing area with CSS width and height. When drawing, the width and height of the drawn graph are scaled according to the scale ratio of the width and height when inserting CSS (so if the scale ratio is different, the drawn graph will be deformed).

But those aren’t the real reasons for the ambiguity. Here’s what’s causing the mess:

When a Canvas is drawn, it starts at the middle of two physical pixels and spreads 0.5 physical pixels to both sides. When equipment than 1 pixel, a 1 px line is in fact occupied two physical pixel (each pixel, in fact, only half), because there is no 0.5 pixel, so the two pixels originally should not be part of the drawing was drawn, then 1 physical pixel lines into 2 physical pixels, creates a blur on the vision

Solving drawing ambiguity

Create the image by magnifying it several times the devicePixelRatio (a new image larger than the original one) and then use CSS to zoom it back down to the original image. Therefore, the reduced image will not exceed its original size and will no longer blur.

var getPixelRatio = function (context) { var backingStore = context.backingStorePixelRatio || context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1; return (window.devicePixelRatio || 1) / backingStore; }; var pixelRatio = getPixelRatio(canvas); Function setCanvasArea(Canvas, CTX) {canvas. Width = math.floor (CW * pixelRatio); canvas.height = Math.floor(ch * pixelRatio); Canvas. Style. width = cw + 'px'; canvas.style.height = ch + 'px'; ctx.scale(pixelRatio, pixelRatio); }Copy the code

anti-aliasing

CanvasRenderingContext2D imageSmoothingEnabled is Canvas 2 d API is used to set the picture whether smooth the properties of the true image smoothing (default), false said the picture is not smooth.

Anti-aliasing is enabled by default and we may want to turn it off to see clear pixels. You can see the effect of the imageSmoothingEnabled property by toggling the checkbox

zoomctx.imageSmoothingEnabled = false;
zoomctx.mozImageSmoothingEnabled = false;
zoomctx.webkitImageSmoothingEnabled = false;
zoomctx.msImageSmoothingEnabled = false;
Copy the code

The first image is drawn at its natural size, the second image is scaled 3x and image smoothing is enabled, and the third image is scaled 3x but image smoothing is disabled.

imageSmoothingQuality

Use the imageSmoothingQuality attribute to adjust the smoothing quality

ctx.imageSmoothingQuality = value
value = ctx.imageSmoothingQuality
//value
//"low","medium","high"
Copy the code

image-rendering

Developer.mozilla.org/zh-CN/docs/…

The CSS property image-rendering is used to set the image scaling algorithm.

/* / image-rendering: auto; image-rendering: crisp-edges; image-rendering: pixelated; /* global attribute value */ image-rendering: inherit; image-rendering: initial; image-rendering: unset;Copy the code

Save the picture

Juejin. Cn/post / 684490…

  • Convert the DOM to a Canvas object

    Html2canvas.hertzen.com/dist/html2c…

  • Generate photos from canvas

    Github.com/randreucett…

performance

  • Avoid floating point coordinates and replace them with integers
  • Cache the different sizes of images in the off-screen Canvas instead of using drawImage() to scale them.

deformation

translate(x, y)

rotate(angle)

scale(x, y)

If it is smaller than 1, it will zoom out. If it is larger than 1, it will zoom in

If the argument is a negative real number, it is equivalent to reversing the image with the x or y axis as the symmetry axis (for example, translate(0,canvas.height); scale(1,-1); The Y-axis is used as the symmetry axis

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

A (m11) horizontal scaling b(m12) vertical tilt offset C (m21) horizontal tilt offset D (m22) Vertical scaling e(dx) Horizontal movement f(dy) vertical movement

combination

Draw order: globalCompositeOperation. This property sets the masking strategy to be used when drawing a new figure

save&&restore

  • Save () Saves all the states of the canvas
  • The restore() save and restore methods save and restore the canvas state with no parameters. The Canvas state is a snapshot of all the styles and distortions applied to the current screen.

Canvas state is stored on the stack, and every time the save() method is called, the current state is pushed to the stack for saving. Each time the restore method is called, the last saved state is popped off the stack and all Settings are restored.

Konva

The working principle of

The object of Konva is stored in the form of a tree. The Konva.Stage is the root node of the tree, and the Stage child node is the Layer created by the user (konva.layer).

Each layer has two < Canvas > renderers: the scene renderer and the image hit detection renderer. The scene renderer outputs what you see, and the image hits the renderer in the hidden Canvas for high performance detection events.

Layers can contain graphics, groups of nested graphics, and groups of nested groups. Stages, layers, groups, and shapes are all virtual nodes, similar to HTML’S DOM nodes.

Node structure diagram:

              Stage
                |
         +------+------+
         |             |
       Layer         Layer
         |             |
   +-----+-----+     Shape
   |           |
 Group       Group
   |           |
   +       +---+---+
   |       |       |
Shape   Group    Shape
           |
           +
           |
         Shape
Copy the code

The sample

  1. Import the konva.js file

    <script src="konva.js"></script>
    Copy the code
  2. A container is then placed in the page as the object that Konva handles. Konva will add the Canvas tag to the container. It’s worth noting that you need to add an ID attribute to this tag.

    <div id="dv"></div>
    Copy the code
  3. Then write the JS code. Konva is a fully object-oriented library.

  4. Create a stage

    var stage = new Konva.Stage({
     container: 'dv',
     width: window.innerWidth,
     height: window.innerHeight
    });
    Copy the code
  • First, all graphs in Konva are a constructor in Konva. Konva is the global namespace.
  • The Stage is created using the Stage constructor, which needs to provide parameters.
  • The parameters for all graphs in Konva are provided using JSON objects.
  • The stage needs to set the container ID, that is, the container property. And width and height.
  1. The stage can be placed in one or more layers, and all shapes should be placed in layers

    • First create the layer object. Layer objects do not need to pass parameters.
    var layer = new Konva.Layer();
    Copy the code
    • Adds layers to the stage. All additions in Konva are made using the add method.

      stage.add( layer );
      Copy the code
  2. Placing a rectangle in a layer creates a rectangle object

    var rect = new Konva.Rect({
    x: 100,
    y: 50,
    width: 200,
    height: 100,
    fill: 'red'
    });
    Copy the code

    Add the rectangle to the layer

    layer.add( rect );
    Copy the code
  3. The final drawing uses the draw method

    layer.draw();
    Copy the code

stage

The concept of layer is similar to layer in Photoshop or Z-index in DOM. When we add a layer to the stage, a canvas element will be added to the DOM to correspond to this layer.

When we call layer.draw when we add multiple shapes to a layer, the layer is drawn in the order in which the shapes were added. The next one is at the top, and the first one is at the bottom.