Canvas game development learning part 2: drawing basic graphics
The grid
Before we really start, we need to discuss the grid or coordinate space of canvas. In the HTML template of the previous page, there is a canvas object that is 150 pixels wide and 150 pixels high. I superimposed the default grid on the screen, as shown on the right. Usually 1 unit of the grid corresponds to 1 pixel on the canvas. The origin of the grid is positioned at the upper left corner (coordinates (0,0)). The positions of all objects in the picture are relative to this origin. In this way, the position of the blue square in the upper left corner is x pixels from the left and Y pixels from the top (coordinates (x, y)). In later tutorials we will learn how to move the origin, rotate and scale the mesh. But for now we will use the default state.
Drawing shapes
canvas only supports one basic shape - rectangle, so other shapes are composed of one or more paths . Fortunately, there is a set of path drawing functions that allow us to draw quite complex shapes.
Rectangles
Let’s look at rectangles first. There are three functions used to draw rectangles:
1 2 3 |
|
They all accept four parameters, x and y Specifies the position of the upper left corner of the rectangle (relative to the origin), width and height are the width and height of the rectangle. Okay, let’s try it out.
Example of drawing a rectangleRectangular shape example
1 2 3 4 5 6 7 8 9 10 |
|
The result should be the same as the one below of. The fillRect
function draws a large black rectangle (100x100), the clearRect
function clears the 60x60 square in the middle, and then the strokeRect
function outlines a 50x50 rectangular border in the cleared space. In the next page, we will see two other methods similar to the clearRect
function, and how to change the fill and border colors of graphics.
Drawing paths drawing paths
Unlike drawing a rectangle, drawing a path requires some extra steps.
1 2 3 4 |
|
The first step is to create a path with beginPath
. In memory, paths are stored in the form of a set of sub-paths (lines, arcs, etc.), which together form a graphic. Each time beginPath
is called, the subpath group is reset and new graphics can then be drawn.
The second step is the actual drawing of the path, as we'll see shortly.
The third step is to call the closePath
method, which will try to connect the current endpoint and the starting endpoint with a straight line to close the path, but if the graphic has been closed or there is only one point, it will do nothing. This step is not necessary.
The last step is to call the stroke or fill method. At this time, the graphics is actually drawn on the canvas. Stroke is the border for drawing graphics, and fill will fill a solid graphics.
Note: When fill is called, the open path will be automatically closed without calling closePath.
The code to draw a simple shape (such as a triangle) is as follows.
1 2 3 4 5 |
|
moveTo
is a very useful method. Although it cannot be used to draw anything, it is part of the practical method of drawing paths. You can think of it as lifting a pen and moving it from one point to another. It accepts x
and y (the new coordinate position) as parameters. When canvas is initialized or beginPath is called, the starting coordinate setting is the origin (0,0). In most cases, we use the moveTo method to move the starting coordinates to other places, or to draw discontinuous paths. Look at the smiley face below. The red line is the trajectory moved using moveTo.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|
我们用lineTo方法来画直线。lineTo方法接受终点的坐标(x,y)作为参数。起始坐标取决于前一路径,前一路径的终点即当前路径的起点,起始坐标也可以通过moveTo方法来设置。示例(如下图)画的是两个三角形,一个实色填充,一个勾边。首先调用beginPath方法创建一个新路径,然后用moveTo方法将起始坐标移至想要的位置,然后画两条直线来构成三角形的两条边。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
弧线 Arcs
我们用arc方法来绘制弧线或圆。标准说明中还包含arcTo方法,当前 Safari 是支持的,但基于 Gecko 的浏览器还未实现。方法接受五个参数:x,y 是圆心坐标,radius 是半径,startAngle和endAngle分别是起末弧度(以 x 轴为基准),anticlockwise为 true 表示逆时针,反之顺时针。警告:在 Firefox 的 beta 版本里,最后一个参数是clockwise,而最终版本不是。因此如果是从 beta 升级至发行版需要做相应修改。
注意:arc方法里用到的角度是以弧度为单位而不是度。度和弧度直接的转换可以用这个表达式:var radians = (Math.PI/180)*degrees;。
1 |
|
arc
的使用示例
这个示例比之前见到过的要复杂一些,画了12个不同的弧形,有不同夹角和填充状态的。如果我用上面画笑脸的方式来画这些弧形,那会是一大段的代码,而且, 画每一个弧形时我都需要知道其圆心位置。像我这里画 90,180 和 270 度的弧形看起来不是很麻烦,但是如果图形更复杂一些,则实现起来会越来越困难。这里使用两个for
循环来画多行多列的弧形。每一个弧形都用beginPath方法创建一个新路径。然后为了方便阅读和理解,我把所有参数都写成变量形式。显而易见,x 和 y 作为圆心坐标。radius和startAngle都是固定,endAngle从 180 度半圆开始,以 90 度方式递增至圆。anticlockwise则取决于奇偶行数。最后,通过 if语句判断使前两行表现为勾边,而后两行为填充效果。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
|
以上就是canvas游戏开发学习之二:绘制基本图形的内容,更多相关内容请关注PHP中文网(www.php.cn)!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Building amazing games using Go involves the following steps: Setting up the project: Create a new project using Git and create the necessary files. Write game logic: Write core game logic in game.go, such as guessing number games. Write the entry point: Create the entry point of the game in main.go, allowing user input and handling guesswork. Compile and run: Compile and run the game. The practical example is a guessing number game. The user can input numbers between 0 and 99 and get feedback.

In today's software development field, Golang (Go language), as an efficient, concise and highly concurrency programming language, is increasingly favored by developers. Its rich standard library and efficient concurrency features make it a high-profile choice in the field of game development. This article will explore how to use Golang for game development and demonstrate its powerful possibilities through specific code examples. 1. Golang’s advantages in game development. As a statically typed language, Golang is used in building large-scale game systems.

C++ is a powerful programming language that is widely used in game development. If you are interested in game development and have a certain programming foundation, then this article will help you get started with C++ game development and implement your own game project from scratch. Step 1: Preparation Before starting, make sure you have installed a C++ compiler, such as Microsoft Visual Studio or Code::Blocks. These tools will help you compile and run your game project. Step 2: Learn

When choosing a Java framework in game development, you should consider the specific needs of your project. Available Java game frameworks include: LibGDX: suitable for cross-platform 2D/3D games. JMonkeyEngine: used to build complex 3D games. Slick2D: Suitable for lightweight 2D games. AndEngine: A 2D game engine developed specifically for Android. Kryonet: Provides network connection capabilities. For 2DRPG games, for example, LibGDX is ideal because of its cross-platform support, lightweight design, and active community.

Explore the Canvas framework: To understand what are the commonly used Canvas frameworks, specific code examples are required. Introduction: Canvas is a drawing API provided in HTML5, through which we can achieve rich graphics and animation effects. In order to improve the efficiency and convenience of drawing, many developers have developed different Canvas frameworks. This article will introduce some commonly used Canvas frameworks and provide specific code examples to help readers gain a deeper understanding of how to use these frameworks. 1. EaselJS framework Ea

To create a 2D game using Go language, follow the following steps: Install Go language. Create a project directory and initialize the Go module. Create a game engine to handle graphics and input. Create a game object. Write the main game program. run game.

Practical cases of Go framework in game development: Technology stack: Gov1.18, Gin framework, MongoDB architecture: Web server (processing HTTP requests), game server (processing game logic and communication), MongoDB database (storing player data) Web server : Use Gin routing to handle player creation and acquisition requests Game server: Handle game logic and player communication, use UNIX sockets for network communication Database: Use MongoDB to store player data, provide the function of creating and obtaining player information Actual case function: create players , obtain players, update player status, and handle player interactions. Conclusion: The Go framework provides efficient

To understand game development and physics engines in JavaScript, specific code examples are required. In recent years, with the rapid development of the Internet, web games have become an important part of people's entertainment lives. As one of the main technologies for Web front-end development, JavaScript plays a decisive role in game development. This article will introduce some basic knowledge about JavaScript game development and physics engines, and provide some specific code examples. Getting Started with Game Development Before proceeding with game development, we first
