Canvas and SVG

Time:2021-11-24

What is SVG?

quotew3cThe last paragraph is:

Svg refers to scalable vector graphics
SVG is used to define vector based graphics for networks
Svg uses XML format to define graphics
When SVG image is enlarged or changed in size, its graphics quality will not be lost


PS: ` SVG 'is supported under IE9, Firefox and chrome

segmentFaultoflogoJust onesvgYou can right-click the page, click “view page information”, find the media, and then find the pagesvgFormattedlogoSave it as:

This is thatsvgcode:

Canvas and SVG
Svg code to<svg>Start of element, including opening label<svg>And close labels</svg>

SVGThere are predefined shape elements that can be used and manipulated by developers:

Rectangle < rect >
Circular < circle >
Ellipse < ellipse >
Line < line >
Polyline < polyline >
Polygon < polygon >
Path < Path >

Rectangular rect

Canvas and SVG

Circular

Canvas and SVG

Elliptical ellipse

Canvas and SVG

Line

Canvas and SVG

Polyline

Canvas and SVG

Polygon

Canvas and SVG

Path tag

Labels are used to define paths.
The following commands are available for path data:

M = moveto
L = lineto
H = horizontal lineto
V = vertical lineto
C = curveto
S = smooth curveto
Q = quadratic Belzier curve
T = smooth quadratic Belzier curveto
A = elliptical Arc
Z = closepath

Note: lowercase letters are allowed for all the above commands. Upper case indicates absolute positioning and lower case indicates relative positioning.

Basic operation API

Create drawing

document.createElementNS(ns,tagName);

Add graphics

element.appendChild(childElement);

Set / get properties

element.setAttribute(name,value);
element.getAttribute(name);

canvas

Similarly, browsers before IE9 do not supportHold < canvas >Elements,canvasandSVGThe main difference is: usecanvasDrawing graphics is done by calling its API, andSVGBy building a treeXMLElement tree.

Canvas API

Color, style, and shadow properties and methods

attribute describe
fillStyle Sets or returns the color, gradient, or mode used to fill a painting
strokeStyle Sets or returns the color, gradient, or mode used for strokes
shadowColor Sets or returns the color used for shadows
shadowBlur Sets or returns the level of blur used for shadows
shadowOffsetY Sets or returns the vertical distance of the shadow from the shape
shadowOffsetX Sets or returns the horizontal distance of the shadow from the shape
ctx.shadowOffsetX = 10; //  Set horizontal displacement
ctx.shadowOffsetY = 10; //  Set vertical displacement
ctx.shadowBlur = 5; //  Set blur
ctx.shadowColor = "rgba(0,0,0,0.5)"; //  Set shadow color

ctx.fillStyle = "#CC0000"; 
ctx.fillRect(10,10,200,100);
method describe
createLinearGradient() Create a linear gradient (used on canvas content)
createPattern() Repeats the specified element in the specified direction
createRadialGradient() Create radial / circular gradient (used on canvas content)
addColorStop() Specifies the color and stop position in the gradient object

Main properties and methods of canvas

attribute describe
save() Saves the state of the current environment
restore() Returns previously saved path States and properties
createEvent()
getContext() Returns an object indicating the API necessary to access the drawing function
toDataURL() Returns the URL of the canvas image

Canvas line style properties and methods

attribute describe
lineCap Sets or returns the end style of the line
lineJoin Sets or returns the type of corner created when two lines intersect
lineWidth Sets or returns the current line width
miterLimit Sets or returns the maximum miter length

Rectangle method

method describe
rect() create rectangles
fillRect() Draws a filled rectangle
strokeRect() Draw rectangle (no fill)
clearRect() Clears the specified pixel within the given rectangle

Path method

method describe
fill() Fill current drawing (path)
stroke() Draw a defined path
beginPath() Start a path, or reset the current path
moveTo() Move the path to the specified point in the canvas without creating a line
closePath() Creates a path from the current point back to the starting point
lineTo() Add a new point and create a line from that point to the last specified point
clip() Cut an area of any shape and size from the original canvas
quadraticCurveTo() Create a quadratic Bezier curve
bezierCurveTo() Create cubic Bezier curve
arc() Create arcs / curves (for creating circles or partial circles)
arcTo() Creates an arc / curve between two tangents
isPointInPath() Returns a Boolean value if the specified point is in the current path
var canvas = document.getElementById('myCanvas');

if (canvas.getContext) {
    var ctx = canvas.getContext('2d');
}
ctx.beginPath(); //  Start path drawing
ctx.moveTo(20, 20); //  Set the starting point of the path, and the coordinates are (20,20)
ctx.lineTo(200, 20); //  Draw a line to (200,20)
ctx.lineWidth = 1.0; //  Set lineweight
ctx.strokeStyle = "#CC0000"; //  Sets the color of the line
ctx.stroke(); //  Shade the line so that the entire line becomes visible

Conversion method

method describe
scale() Zooms the current drawing to a larger or smaller size
rotate() Rotate current drawing
translate() Remap (0,0) position on canvas
transform() Replace the current conversion matrix of the drawing
setTransform() Resets the current conversion to the identity matrix. Then run transform ()

Text properties and methods

attribute describe
font Sets or returns the current font property of the text content
textAlign Sets or returns the current alignment of the text content
textBaseline Sets or returns the current text baseline used when drawing text
method describe
fillText() Draw the filled text on the canvas
strokeText() Draw text on canvas (no fill)
measureText() Returns an object containing the specified text width
//Set font
ctx.font = "Bold 20px Arial"; 
//Set alignment
ctx.textAlign = "left";
//Set fill color
ctx.fillStyle = "#008600"; 
//Set font内容,以及在画布上的位置
ctx.fillText("Hello!", 10, 50); 
//Draw empty words
ctx.strokeText("Hello!", 10, 100);

Image rendering method

method describe
drawImage() Drawing an image, canvas, or video onto a canvas is not supported in chrome

Pixel operation methods and properties

attribute describe
width Returns the width of the imagedata object
height Returns the height of the imagedata object
data Returns an object that contains the image data of the specified imagedata object
method describe
createImageData() Create a new, blank imagedata object
getImageData() Returns an imagedata object that copies pixel data for the rectangle specified on the canvas
putImageData() Put the image data (from the specified imagedata object) back on the canvas

Image composition properties

attribute describe
globalAlpha Sets or returns the current alpha or transparent value of the plot
globalCompositeOperation Sets or returns how a new image is drawn onto an existing image

When to use canvas and SVG?

Choose from performance

Performance is absolutely critical for high traffic websites. althoughCanvasIt is generally considered to have high performance, but it does not mean that it is an obvious choice. The following figure showsSVGObject andCanvasThe difference in rendering time between objects.

Canvas and SVG
Generally, as the screen size increases, the canvas will begin to degrade because more pixels need to be drawn. As the number of objects on the screen increases,SVGWill start demoting because we are constantly adding these objects toDOMYes. These metrics are not necessarily accurate, and differences in implementation and platform, whether to use fully hardware accelerated graphics, andjsThe speed of the engine.

The following figure shows a suitable forcanvasScenarios andsvgSuitable scenarios:
Canvas and SVG

CanvasIs rendered pixel by pixel. staySVGIn, each drawing is treated as an object. IfSVGIf the properties of the object change, the browser can automatically reproduce the drawing.

Canvas

Resolution dependent
Event handler is not supported
Weak text rendering ability
The result image can be saved in. PNG or. JPG format
Most suitable for image intensive games, in which many objects will be redrawn frequently

SVG

Resolution independent
Support event handler
Best for applications with large rendering areas (such as Google Maps)
High complexity slows down rendering (any application that overuses DOM is not fast)
Not suitable for game applications

Recommended Today

Seven solutions for distributed transactions

1、 What is distributed transaction Distributed transaction means that transaction participants, transaction supporting servers, resource servers and transaction managers are located on different nodes of different distributed systems. A large operation is completed by more than n small operations. These small operations are distributed on different services. For these operations, either all of them are […]