Home Web Front-end H5 Tutorial Canvas Game Development Learning Part 5: Using Styles and Colors (1)

Canvas Game Development Learning Part 5: Using Styles and Colors (1)

Jan 16, 2017 pm 05:49 PM

So far, we have only seen methods for drawing content. If we want to color graphics, there are two important properties that can do it: fillStyle
and strokeStyle.

fillStyle = color
strokeStyle = color
Copy after login


trokeStyle is used to set the color of the graphic outline, and fillStyle is used to set the fill color. color can be a string representing a CSS color value, a gradient object, or a pattern object. We'll come back to gradients and pattern objects later. By default, the line and fill colors are black (CSS color value #000000). What you enter should be a valid string that conforms to the CSS3 color value standard. The examples below all represent the same color.

// 这些 fillStyle 的值均为 '橙色'  
 ctx.fillStyle = "orange";  
 ctx.fillStyle = "#FFA500";  
 ctx.fillStyle = "rgb(255,165,0)";  
 ctx.fillStyle = "rgba(255,165,0,1)"
Copy after login

Note: Currently, the Gecko engine does not provide support for all CSS 3 color values. For example, hsl(100%,25%,0) or rgb(0,100%,0) are not available. But if you follow the conventions of the example above, you should have no problem. Once you change the value of strokeStyle or fillStyle, the new value will become the default value for newly drawn graphics. If you want to give each shape a different color, you need to reset the fillStyle or strokeStyle
value.

fillStyle
Example

In this example, I will again use a two-level for
loop to draw an array of squares, each square a different color. The result is as shown on the right, but the code used to implement it is not so colorful. I used two variables i and j to generate a unique RGB color value for each square, where only the red and green channel values ​​were modified, leaving the blue channel value unchanged. You can produce a variety of color palettes by modifying the values ​​of these color channels. By increasing the frequency of the gradient, you can also draw a color palette similar to the one in Photoshop.

Canvas Game Development Learning Part 5: Using Styles and Colors (1)

function draw() {  
   var ctx = document.getElementById('canvas').getContext('2d');  
   for (var i=0;i<6;i++){  
     for (var j=0;j<6;j++){  
       ctx.fillStyle = &#39;rgb(&#39; + Math.floor(255-42.5*i) + &#39;,&#39; +   
                        Math.floor(255-42.5*j) + &#39;,0)&#39;;  
       ctx.fillRect(j*25,i*25,25,25);  
     }  
   }  
 }
Copy after login

strokeStyle
Example

This example is somewhat similar to the above, but this time the strokeStyle attribute is used, and the drawing is not square. Grid, but use arc method to draw circles.


Canvas Game Development Learning Part 5: Using Styles and Colors (1)

function draw() {  
     var ctx = document.getElementById(&#39;canvas&#39;).getContext(&#39;2d&#39;);  
     for (var i=0;i<6;i++){  
       for (var j=0;j<6;j++){  
         ctx.strokeStyle = &#39;rgb(0,&#39; + Math.floor(255-42.5*i) + &#39;,&#39; +   
                          Math.floor(255-42.5*j) + &#39;)&#39;;  
         ctx.beginPath();  
         ctx.arc(12.5+j*25,12.5+i*25,10,0,Math.PI*2,true);  
         ctx.stroke();  
       }  
     }  
   }
Copy after login

Transparency

In addition to drawing solid color graphics, we can also use canvas to draw translucent ones graphics. By setting the globalAlpha
property or using a translucent color as an outline or fill style.

globalAlpha = transparency value
Copy after login

This property affects the transparency of all graphics in the canvas. The valid value range is 0.0 (completely transparent) to 1.0 (completely opaque). The default is 1.0. The globalAlpha
property is very efficient when drawing a large number of graphics with the same transparency. However, I think the following method is more feasible. Because the strokeStyle and fillStyle properties accept color values ​​​​that comply with the CSS 3 specification, we can use the following writing method to set a color with transparency.

// Assigning transparent colors to stroke and fill style  
  ctx.strokeStyle = "rgba(255,0,0,0.5)";  
  ctx.fillStyle = "rgba(255,0,0,0.5)";
Copy after login

The rgba() method is similar to the rgb() method, with one more parameter for setting color transparency. Its valid range is from 0.0 (fully transparent) to 1.0 (fully opaque).

globalAlpha
Example

In this example, I use a four-color grid as the background. After setting globalAlpha
to 0.2, I draw a series of translucent circles with increasing radii on it. . The end result is a radial gradient effect. The more circles you add, the less transparent the originally drawn circle will be. By increasing the number of loops and drawing more circles, the center part of the background image will disappear completely.

Canvas Game Development Learning Part 5: Using Styles and Colors (1)

function draw() {  
   var ctx = document.getElementById(&#39;canvas&#39;).getContext(&#39;2d&#39;);  
   // draw background  
   ctx.fillStyle = &#39;#FD0&#39;;  
   ctx.fillRect(0,0,75,75);  
   ctx.fillStyle = &#39;#6C0&#39;;  
   ctx.fillRect(75,0,75,75);  
   ctx.fillStyle = &#39;#09F&#39;;  
   ctx.fillRect(0,75,75,75);  
   ctx.fillStyle = &#39;#F30&#39;;  
   ctx.fillRect(75,75,150,150);  
   ctx.fillStyle = &#39;#FFF&#39;;  
   
   // set transparency value  
   ctx.globalAlpha = 0.2;  
   
   // Draw semi transparent circles  
   for (var i=0;i<7;i++){  
       ctx.beginPath();  
       ctx.arc(75,75,10+10*i,0,Math.PI*2,true);  
       ctx.fill();  
   }  
 }
Copy after login

rgba()示例

第二个例子和上面那个类似,不过不是画圆,而是画矩形。这里还可以看出,rgba()可以分别设置轮廓和填充样式,因而具有更好的可操作性和使用弹性。

Canvas Game Development Learning Part 5: Using Styles and Colors (1)

function draw() {  
      var ctx = document.getElementById(&#39;canvas&#39;).getContext(&#39;2d&#39;);  
      
      // Draw background  
      ctx.fillStyle = &#39;rgb(255,221,0)&#39;;  
      ctx.fillRect(0,0,150,37.5);  
      ctx.fillStyle = &#39;rgb(102,204,0)&#39;;  
      ctx.fillRect(0,37.5,150,37.5);  
      ctx.fillStyle = &#39;rgb(0,153,255)&#39;;  
      ctx.fillRect(0,75,150,37.5);  
      ctx.fillStyle = &#39;rgb(255,51,0)&#39;;  
      ctx.fillRect(0,112.5,150,37.5);  
     
     // Draw semi transparent rectangles  
      for (var i=0;i<10;i++){  
        ctx.fillStyle = &#39;rgba(255,255,255,&#39;+(i+1)/10+&#39;)&#39;;  
        for (var j=0;j<4;j++){  
          ctx.fillRect(5+i*14,5+j*37.5,14,27.5)  
        }  
      }  
    }
Copy after login

以上就是canvas游戏开发学习之五:运用样式与颜色(一)的内容,更多相关内容请关注PHP中文网(www.php.cn)!


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1663
14
PHP Tutorial
1263
29
C# Tutorial
1236
24
Build amazing games with Go Build amazing games with Go Apr 08, 2024 am 10:24 AM

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.

Master how Golang enables game development possibilities Master how Golang enables game development possibilities Mar 16, 2024 pm 12:57 PM

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.

Learn the canvas framework and explain the commonly used canvas framework in detail Learn the canvas framework and explain the commonly used canvas framework in detail Jan 17, 2024 am 11:03 AM

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

How to choose a Java framework for game development How to choose a Java framework for game development Jun 06, 2024 pm 04:16 PM

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.

uniapp implements how to use canvas to draw charts and animation effects uniapp implements how to use canvas to draw charts and animation effects Oct 18, 2023 am 10:42 AM

How to use canvas to draw charts and animation effects in uniapp requires specific code examples 1. Introduction With the popularity of mobile devices, more and more applications need to display various charts and animation effects on the mobile terminal. As a cross-platform development framework based on Vue.js, uniapp provides the ability to use canvas to draw charts and animation effects. This article will introduce how uniapp uses canvas to achieve chart and animation effects, and give specific code examples. 2. canvas

Practical cases of golang framework in game development Practical cases of golang framework in game development Jun 02, 2024 am 09:23 AM

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

Introduction to C++ game development: implement your own game project from scratch Introduction to C++ game development: implement your own game project from scratch Nov 27, 2023 am 10:41 AM

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

Learn about game development and physics engines in JavaScript Learn about game development and physics engines in JavaScript Nov 03, 2023 am 09:54 AM

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

See all articles