


Tutorial on using HTML5 Canvas to fill images with color and texture_html5 tutorial tips
Fill Color
Art is inseparable from color. Today we will introduce filling color and experience the charm of color.
There are two main types of fill colors:
1. Basic color
2. Gradient color (also divided into linear gradient and radial gradient)
Let’s look at them one by one.
Fill basic color
The Canvas fillStyle property is used to set the basic color and fill of the shape on the canvas. fillStyle uses simple color names. This looks very simple, for example:
- context.fillStyle = "red";
The following is a list of sixteen available color string values from the HTML4 specification. Since HTML5 does not modify the exclusive colors, HTML4 colors can be displayed correctly in HTML5.
All of these color values can be applied to the strokeStyle and fillStyle properties.
Okay, let me summarize the method of filling basic colors: (can also be used for strokeStyle attribute)
(1) Use color string filling.
- context.fillStyle = "red";
(2) Use hexadecimal digit string padding.
- context.fillStyle = "#FF0000";
(3) Fill with hexadecimal digit string abbreviation.
- context.fillStyle = "#F00";
(4) Use the rgb() method to set the color.
- context.fillStyle = "rgb(255,0,0)";
(5) Use the rgba() method to set the color.
JavaScript CodeCopy content to clipboard
- context.fillStyle = "rgba(255,0,0,1)";
The last parameter of this method is the alpha value, and the transparency range is 1 (opaque) ~ 0 (transparent).
(6) Use the hsl() method to set the color.
- context.fillStyle = "hsl(0,100%,50%)";
HSL represents the color of the three channels of hue (H), saturation (S), and lightness (L).
(7) Use the hsla() method to set the color.
- context.fillStyle = "hsla(0,100%,50%,1)";
The above 7 sentences of code are all filled with "#FF0000" in red.
Fill Gradient Shape
There are two basic options for creating a gradient fill on the canvas: linear or radial. Linear gradients create a horizontal, vertical, or diagonal fill pattern. Radial gradients create a radial fill from a center point. There are three steps to filling a gradient shape: add a gradient line, add a key color to the gradient line, and apply the gradient. Here are some examples of them.
Linear Gradient
Three Step Strategy:
Add Gradient Lines:
- var grd = context.createLinearGradient(xstart,ystart,xend,yend);
Add a key color to the gradient line (similar to a color breakpoint):
- grd.addColorStop(stop,color);
The stop here is a floating point number from 0 to 1, which represents the proportion of the distance from the breakpoint to (xstart, ystart) to the entire gradient length.
Apply gradient:
- context.fillStyle = grd;
- context.strokeStyle = grd;
Write a code to take a look.
- "zh">
- "UTF-8">
-
Fill linear gradient - "canvas-warp">
- Your browser doesn’t support Canvas? ! Change it quickly! !
- <script> </script>
- window.onload = function(){
- var canvas = document.getElementById("canvas");
- canvas.width = 800;
- canvas.height = 600;
- var context = canvas.getContext("2d");
- context.rect(200,100,400,400);
- //Add gradient line
- var grd = context.createLinearGradient(200,300,600,300);
- //Add color breakpoints
- grd.addColorStop(0,"black");
- grd.addColorStop(0.5,"white");
- grd.addColorStop(1,"black");
- //Apply gradient
- context.fillStyle = grd;
- context.fill();
- }
Run result:
I think it is necessary to make an illustration so that everyone can understand the gradient at one time.
In order to facilitate understanding, it is recommended to regard the gradient line as a directed line segment. If you are familiar with drawing tools such as PS and have used the gradient settings, you should have a good understanding.
The starting point and end point of the gradient line here do not have to be within the image, and the position of the color breakpoint is the same. But if the range of the image is larger than the gradient line, then outside the range of the gradient line, the color of the breakpoint closest to the endpoint will be automatically filled.
Here is another example with two supplementary functions.
Quick way to draw a rectangle
- fillRect(x,y,width,height)、stroke(x,y,width,height)。这两个函数可以分别看做rect()与fill()以及rect()与stroke()的组合。因为rect()仅仅只是规划路径而已,而这两个方法确实实实在在的绘制。
- nbsp;html>
- "zh">
- "UTF-8">
-
填充线性渐变 - "canvas-warp">
- 你的浏览器居然不支持Canvas?!赶快换一个吧!!
- <script> </script>
- window.onload = function(){
- var canvas = document.getElementById("canvas");
- canvas.width = 800;
- canvas.height = 600;
- var context = canvas.getContext("2d");
- //Add gradient line
- var grd = context.createLinearGradient(100,300,700,300);
- //Add color breakpoints
- grd.addColorStop(0,"olive");
- grd.addColorStop(0.25,"maroon");
- grd.addColorStop(0.5,"aqua");
- grd.addColorStop(0.75,"fuchsia");
- grd.addColorStop(0.25,"teal");
- //Apply gradient
- context.fillStyle = grd;
- context.strokeStyle = grd;
- context.strokeRect(200,50,300,50);
- context.strokeRect(200,100,150,50);
- context.strokeRect(200,150,450,50);
- context.fillRect(200,300,300,50);
- context.fillRect(200,350,150,50);
- context.fillRect(200,400,450,50);
- context.fillRect(0,550,800,25);
- }
Run result:
Both pages have horizontal gradients, but it should be clear that linear gradients are not necessarily horizontal, and the direction can be arbitrary. The direction is set through the endpoints of the gradient line.
Radial Gradient
It is also a three-step strategy, but the method used in the first step has changed.
Add gradient circle:
- var grd = context.createRadialGradient(x0,y0,r0,x1,y1,r1);
Add a key color to the gradient line (similar to a color breakpoint):
- grd.addColorStop(stop,color);
Apply gradient:
- context.fillStyle = grd;
- context.strokeStyle = grd;
A linear gradient is defined based on two endpoints, but a radial gradient is defined based on two circles.
Let’s rewrite Example 7-2.
- "zh">
- "UTF-8">
-
Fill Radial Gradient - "canvas-warp">
- Your browser doesn’t support Canvas? ! Change it quickly! !
- <script> </script>
- window.onload = function(){
- var canvas = document.getElementById("canvas");
- canvas.width = 800;
- canvas.height = 600;
- var context = canvas.getContext("2d");
- //Add gradient line
- var grd = context.createRadialGradient(400,300,100,400,300,200);
- //Add color breakpoints
- grd.addColorStop(0,"olive");
- grd.addColorStop(0.25,"maroon");
- grd.addColorStop(0.5,"aqua");
- grd.addColorStop(0.75,"fuchsia");
- grd.addColorStop(0.25,"teal");
- //Apply gradient
- context.fillStyle = grd;
- context.fillRect(100,100,600,400);
- }
Run result:
Why do you feel that this color combination is so...forget it, this is called art.
createRadialGradient(x0,y0,r0,x1,y1,r1); method specifies the start and end range of the radial gradient, that is, the gradient between two circles.
To summarize, in this lesson we learned about fillStyle, createLinearGradient(), createRadialGradient(), addColorStop(), fillRect(), strokeRect() and other attributes and methods, and introduced in detail the filling of basic colors, linear gradients, and radial gradient.
Okay, now that we have learned how to color, let’s use colors to our heart’s content and draw our own artwork!
Fill texture
Introduction to createPattern()
Texture is actually a repetition of the pattern, and the fill pattern is initialized through the createPattern() function. It needs to pass in two parameters createPattern(img,repeat-style), the first is an Image object instance, and the second parameter is a String type, indicating how to display the repeat pattern in the shape. You can use this function to load an image or the entire canvas as a fill pattern for a shape.
There are the following 4 image fill types:
1. Repeat on the plane: repeat;
2. Repeat on the x-axis: repeat-x;
3. Repeat on the y-axis: repeat-y;
4. Do not use repeat: no- repeat;
In fact, the first parameter of createPattern() can also be passed in a canvas object or video object. Here we only explain the Image object, and you can try the rest by yourself.
Create and fill patterns
First look at how to load images:
Create an Image object
Specify the image source for the Image object
The code is as follows:
- var img = new Image(); //Create Image object
- img.src = "8-1.jpg"; //Specify the image source for the Image object
Extension: The relative path in HTML
'../directory or file name' or 'directory or file name' refers to the path of the directory where the currently operated file is located
'../directory or file name' It refers to the path of the directory above the directory where the currently operated file is located
Fill texture afterwards:
- var pattern = context.createPattern(img,"repeat");
- context.fillStyle = pattern;
Let’s look directly at a complete program. Here I want to repeatedly fill in this cute giraffe as a texture. It should be noted that when selecting pictures, you must choose pictures that communicate with each other from left to right and from top to bottom as texture, so that there will be no unnatural short connections.
Code provided below.
- "zh">
- "UTF-8">
-
Fill texture - "canvas-warp">
- Your browser doesn’t support Canvas? ! Change it quickly! !
- <script> </script>
- window.onload = function(){
- var canvas = document.getElementById("canvas");
- canvas.width = 800;
- canvas.height = 600;
- var context = canvas.getContext("2d");
- var img = new Image();
- img.src = "8-1.jpg";
- img.onload = function(){
- var pattern = context.createPattern(img, "repeat");
- context.fillStyle = pattern;
- context.fillRect(0,0,800,600);
- }
The onload event of Image is used here. Its function is to preload the image, that is, the code body of the subsequent function will be removed immediately after the image is loaded. This is necessary, if not written, the canvas will display a black screen. Because the texture is filled without waiting for the image to be loaded, the browser cannot find the image.

Web standards and technologies have evolved from HTML4, CSS2 and simple JavaScript to date and have undergone significant developments. 1) HTML5 introduces APIs such as Canvas and WebStorage, which enhances the complexity and interactivity of web applications. 2) CSS3 adds animation and transition functions to make the page more effective. 3) JavaScript improves development efficiency and code readability through modern syntax of Node.js and ES6, such as arrow functions and classes. These changes have promoted the development of performance optimization and best practices of web applications.

H5 is not just the abbreviation of HTML5, it represents a wider modern web development technology ecosystem: 1. H5 includes HTML5, CSS3, JavaScript and related APIs and technologies; 2. It provides a richer, interactive and smooth user experience, and can run seamlessly on multiple devices; 3. Using the H5 technology stack, you can create responsive web pages and complex interactive functions.

H5 and HTML5 refer to the same thing, namely HTML5. HTML5 is the fifth version of HTML, bringing new features such as semantic tags, multimedia support, canvas and graphics, offline storage and local storage, improving the expressiveness and interactivity of web pages.

H5referstoHTML5,apivotaltechnologyinwebdevelopment.1)HTML5introducesnewelementsandAPIsforrich,dynamicwebapplications.2)Itsupportsmultimediawithoutplugins,enhancinguserexperienceacrossdevices.3)SemanticelementsimprovecontentstructureandSEO.4)H5'srespo

The tools and frameworks that need to be mastered in H5 development include Vue.js, React and Webpack. 1.Vue.js is suitable for building user interfaces and supports component development. 2.React optimizes page rendering through virtual DOM, suitable for complex applications. 3.Webpack is used for module packaging and optimize resource loading.

HTML5hassignificantlytransformedwebdevelopmentbyintroducingsemanticelements,enhancingmultimediasupport,andimprovingperformance.1)ItmadewebsitesmoreaccessibleandSEO-friendlywithsemanticelementslike,,and.2)HTML5introducednativeandtags,eliminatingthenee

H5 improves web page accessibility and SEO effects through semantic elements and ARIA attributes. 1. Use, etc. to organize the content structure and improve SEO. 2. ARIA attributes such as aria-label enhance accessibility, and assistive technology users can use web pages smoothly.

"h5" and "HTML5" are the same in most cases, but they may have different meanings in certain specific scenarios. 1. "HTML5" is a W3C-defined standard that contains new tags and APIs. 2. "h5" is usually the abbreviation of HTML5, but in mobile development, it may refer to a framework based on HTML5. Understanding these differences helps to use these terms accurately in your project.


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

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

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.