Understand the canvas element and draw simple 2D graphics

1. Introduction to canvas

Graphics and animation have increasingly become essential features in modern web applications in browsers, but they remain difficult to implement without slowing down the browser. There is an increasingly sophisticated set of APTs and tools that can be used to develop such capabilities.

There is no doubt that <canvas> is the most popular new feature of HTML5. ​Canvas is a drawable area defined by HTML code with height and width attributes. JavaScript code can access this area to dynamically draw pictures on it, similar to other general 2D APIs, which dynamically generate graphics through a complete set of drawing functions. <canvas> was first proposed by Apple and prepared for use in control panels. As other browsers quickly followed, HTML5 incorporated it into the standard. All major browsers currently support the <canvas> element to some extent.

2. Basic use of Canvas

2.1 <canvas> element

When creating a <canvas> element, you must at least set its width and height attributes so that you can tell the browser how large an area to draw on. The content that appears between the opening and closing tags is fallback data and will be displayed if the browser does not support the <canvas> element. for example:

<canvas id="drawing" width="200" height="200">A drawing of something.</canvas>

Like other elements, the width and height attributes can be set on DOM nodes and therefore can be modified at any time. The entire element can also be styled via CSS, and the element is invisible until the style is added or the content is actually drawn.

To draw graphics on the canvas, you must first obtain the drawing context. Use the getcontext() method to obtain a reference to the drawing context. For flat graphics, you need to pass the parameter "2d" to this method, which means you want to get the 2D context object:

let drawing = document.getElementById("drawing");

// 确保浏览器支持<canvas>

if(drawing.getContext){

    let context = drawing.getContext("2d");

    // 其他代码

}

When using the <canvas> element, it is best to test whether the getContext() method exists first. Some browsers create default HTML element objects for elements that are not in the HTML specification. This means that even if the drawing contains a valid element reference, the getContext () method may not exist.

Images on the <canvas> element can be exported using the toDatauRL() method. This method accepts one parameter: the MIME type of the image to be generated (independent of the context used to create the graphic). For example, to export an image in PNG format from canvas, you can do this:

let drawing = document.getElementById("drawing");

// 确保浏览器支持<canvas>

if (drawing.getContext){

    // 取得图像的数据 URI

    let imgURI = drawing.toDataURL("image/png");

    // 显示图片

    let image = document.createElement("img");

    image.src = imgURI;

    document.body.appendChild(image);

}

Browsers encode images into PNG format by default unless specified otherwise. Firefox and Opera also support passing "image/jpeg" for JPEG encoding. Because this method was added to the specification later, supported browsers were also implemented in later versions, including IE9, Firefox 3.5, and Opera 10.

2.2 A simple example

The following example draws two rectangles:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Canvas入门</title>
<style type="text/css">
canvas {
    border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="tutorial" width="300" height="300"></canvas>
<script type="text/javascript">
function draw(){
    var canvas = document.getElementById('tutorial');
    if(!canvas.getContext) return;
    var ctx = canvas.getContext("2d");
    ctx.fillStyle = "rgb(200,0,0)";
      //绘制矩形
    ctx.fillRect (10, 10, 55, 50);
 
    ctx.fillStyle = "rgba(0, 0, 200, 0.5)";
    ctx.fillRect (30, 30, 55, 50);
}
draw();
</script>
</body>
</html>

operation result:

 

3. Draw shapes

3.1 Grid and coordinate space

As shown in the figure below, the canvas element is covered by the grid by default. Generally speaking, one cell in the grid is equivalent to one pixel in the canvas element. The starting point of the grid is the upper left corner, with coordinates (0,0). All elements are positioned relative to the origin. Therefore, the coordinates of the upper left corner of the blue square in the picture are x pixels from the left (X axis) and y pixels from the top (Y axis). The coordinates are (x, y).

Later we will involve the translation of the coordinate origin, the rotation and scaling of the grid, etc.

 

Guess you like

Origin blog.csdn.net/weixin_43361722/article/details/130814591