search
HomeWeb Front-endH5 TutorialDetailed introduction to HTML5 new label Canvas

1. Overview

Canvas is used to display images on web pages , and the content can be customized. Basically it is a bitmap that can be operated with JavaScript

Canvas API is used to generate images in real time on web pages, JavaScript. Manipulate image content through API. The advantages of this are: reducing the number of HTTP requests, reducing downloaded data, speeding up web page loading time, and enabling real-time processing of images.

Before use, you first need to build a Canvas. Web page element.

<canvas id="myCanvas" width="400" height="200">
    您的浏览器不支持canvas!
</canvas>

If the browser does not support canvas, the text in the middle of the canvas tag will be displayed - "Your browser does not support canvas!"

Then, . Use JavaScript to get the DOM object of canvas.

var canvas = document.getElementById(&#39;myCanvas&#39;);

Next, check whether the browser supports the Canvas API by seeing if the getContext method is deployed. Use the getContext('2d') method to initialize the context of the flat image.

if (canvas.getContext) {    //some code here}

Now the flat image is generated in the middle of the canvas.

( 1) Fill color

Set the fill color.

var ctx = canvas.getContext(&#39;2d&#39;);

(2) Draw a rectangle

## Draw a solid rectangle. ##Draw a hollow rectangle

ctx.fillStyle = "#000000";//设置填充色为黑色ctx.strokeStyle = "#FF6600"; //设置笔触颜色

Clear the contents of a rectangular area

ctx.fillStyle = "#000000";//填充颜色,即矩形颜色ctx.fillRect(x, y, width, height);

(3) Draw a path

ctx.strokeStyle = "#FF6600"; //笔触颜色,即矩形边框颜色ctx.strokeRect(x, y, width, height);

(4) Drawing circles and sectors

Methods for drawing sectors.

ctx.clearRect(x, y, width, height);

The x and y parameters of the arc method are the coordinates of the center of the circle, radius is the radius, and startAngle and endAngle are. It is the starting angle and ending angle of the sector (expressed in degrees). anticlockwise indicates whether the drawing should be drawn counterclockwise (true) or clockwise (false)

Draw a solid circle. #

ctx.beginPath(); //开始路径绘制
ctx.moveTo(20, 20); //设置路径起点
ctx.lineTo(200, 20); //绘制一条到200, 20的直线
ctx.lineWidth = 1.0; //设置线宽
ctx.strokeStyle = "#CC0000"; //设置线的颜色
ctx.stroke(); //进行线的着色,这时整条线才变得可见
Draw a hollow circle

ctx.arc(x, y, radius, startAngle, endAngle, anticlockwise);

(5) Draw text

##The fillText method is used to add text, and the strokeText method is used. Before adding hollow words, you need to set the font, text direction, color and other

properties

. The

ctx.beginPath();

ctx.arc(60, 60, 50, 0, Math.PI*2, true);

ctx.fillStyle = "#000000";

ctx.fill();
fillText method does not support text line breaks, that is, all text appears in one line. So if you want to generate multiple lines of text, you can only call the fillText method multiple times.

2.1 GradientSet the gradient color.

ctx.beginPath();

ctx.arc(60, 60, 50, 0, Math.PI*2, true);

ctx.lineWidth = 1.0;

ctx.strokeStyle = "#000";

ctx.stroke();

The reference of the createLinearGradient method is (x1, y1, x2, y2), where x1 and y1 are the starting point coordinates, and x2 and y2 are the end point coordinates. Through different coordinate values, gradients from top to bottom, left to right, etc. can be generated.

The parameters of the addColorStop method are (offset, color), where offset is a floating point value ranging from 0.0 to 1.0, representing the part between the start point and the end point of the gradient, offset 0 corresponds to the starting point, offset is 1 corresponding to the end point, and color is a string representation of the CSS color value.

The usage method is as follows:

ctx.font = "Bold 20px Arial"; //设置字体
ctx.textAlign = "left"; //设置对齐方式
ctx.fillStyle = "#008600"; //设置填充颜色
ctx.fillText("Hello!", 10, 50); //设置字体内容,以及在画布上的位置
ctx.strokeText("Hello!", 10, 100); //绘制空心字

2.2 Shadow

var myGradient = ctx.createLinearGradient(0, 0, 0, 160);

myGradient.addColorStop(0, "#BABABA");

myGradient.addColorStop(1, "#636363");

3, Image processingMethod

3.1 Insert image

canvas allows you to insert image files into the canvas. After reading the image, use the drawImage method to redraw it in the canvas.

ctx.fillStyle = myGradient;

ctx.fillRect(10, 10, 200, 100);

Since the loading of the image takes time, the drawImage method can only be called after the image is completely loaded, so the above code needs to be rewritten.

ctx.shadowOffsetX = 10; //设置水平位移
ctx.shadowOffsetY = 10; //设置垂直位移
ctx.shadowBlur = 5; //设置模糊度
ctx.shadowColor = "rgba(0, 0, 0, 0.5)"; //设置阴影颜色
ctx.fillStyle = "#CC0000";

ctx.fillRect(10, 10, 200, 100);

The drawImage() method accepts three parameters. The first parameter is the DOM element of the image file (i.e.

img tag

), the second and third The first parameter is the coordinate of the upper left corner of the image in the canvas element. (0, 0) in the above example means placing the upper left corner of the image in the upper left corner of the canvas element.

3.2 Read the contents of CanvasThe getImageData method can be used to read the contents of Canvas and return an object containing the information of each pixel.

var img = new Image();

img.src = "image.png";

ctx.drawImage(img, 0, 0); //设置对应的图像对象,以及它在画布上的位置

The imageData object has a data attribute, and its value is a one-dimensional array. The value of this array is the red, green, blue, and alpha channel values ​​of each pixel in sequence. Therefore, the length of the array is equal to the pixel width of the image * the pixel height of the image * 4, and the range of each value is 0~255. This array is not only readable, but also writable, so by manipulating the values ​​of this array, you can achieve the purpose of operating images. After modifying this array, use the putImageData method to rewrite the array contents back to the Canvas.

var image = new Image();

image.onload = function() {    if (image.width != canvas.width) {
        canvas.width = image.width;
    }    if (image.height != canvas.height) {
        canvas.height = image.height;
    }

    ctx.clearRect(0, 0, canvas.width, canvas.height);

    ctx.drawImage(image, 0, 0);

}

image.src = "image.png";

3.3 Pixel processing

Assuming that filter is a

function

that processes pixels, then the entire Canvas processing process can be represented by the following code.

var imageData = context.getImageData(0, 0, canvas.width, canvas.height);
The following are several common processing methods.

(1)灰度效果

灰度图(grayscale)就是取红、绿、蓝三个像素值的算术平均值,这实际上将图像转成了黑白形式。假定d[i]是像素数组中一个像素的红色值,则d[i+1]为绿色值,d[i+2]为蓝色值,d[i+3]就是alpha通道值。转成灰度的算法,就是将红、绿、蓝三个值相加后除以3,再将结果写回数组。

grayscale = function(pixels) {    
var d = pixels.data;    
for (var i = 0; i < d.length; i += 4) {        
var r = d[i];        
var g = d[i + 1];        
var b = d[i + 2];
        d[i] = d[i + 1] = d[i + 2] = (r + g + b) / 3;
    }    return pixels;

}

(2)复古效果

复古效果(sepia)则是将红、绿、蓝三个像素,分别取这三个值的某种加权平均值,使得图像有一种古旧的效果。

sepia = function(pixels) {    
var d = pixels.data;    
for (var i = 0; i < d.length; i +=4) {        
var r = d[i];        
var g = d[i + 1];        
var b = d[i + 2];
        d[i] = (r * 0.393) + (g * 0.769) + (b * 0.189); //red
        d[i + 1] = (r * 0.349) + (g * 0.686) + (b * 0.168); //green
        d[i + 2] = (r * 0.272) + (g * 0.534) + (b * 0.131); //blue    
        }    
        return pixels;

}

(3)红色蒙版效果

红色蒙版指的是,让图像呈现一种偏红的效果。算法是将红色通道设为红、绿、蓝三个值的平均值,而将绿色通道和蓝色通道都设为0。

red = function(pixels) {    
var d = pixels.data;    
for (var i = 0; i < d.length; i += 4) {        
var r = d[i];        
var g = d[i + 1];        
var b = d[i + 2];
        d[i] = (r + g + b) / 3; //红色通道取平均值
        d[i + 1] = d[i + 2] = 0;
    }    return pixels;

}

(4)亮度效果

亮度效果(brightness)是指让图像变得更亮或更暗。算法将红色通道、绿色通道、蓝色通道,同时加上一个正值或负值。

brightness = function(pixels, delta) {    
var d = pixels.data;    
for (var i = 0; i < d.length; i += 4) {
        d[i] += delta; //red
        d[i + 1] += delta; //green
        d[i + 2] += delta; //blue    
        }    
        return pixels;

}

(5)反转效果

反转效果(invert)是指图片呈现一种色彩颠倒的效果。算法为红、绿、蓝通道都取各自的相反值(255 - 原值)。

invert = function(pixels) {    
var d = pixels.data;    
    for (var i = 0; i < d.length; i += 4) {
        d[i] = 255 - d[i];
        d[i + 1] = 255 - d[i + 1];
        d[i + 2] = 255 - d[i + 2];
    }    return pixels;

}

3.4 将Canvas转化为图像文件

对图像数据作出修改以后,可以使用toDataURL方法,将Canvas数据重新转化成一般的图像文件形式。

<p style="margin-bottom: 7px;">function convertCanvasToImage(canvas) {    <br/>var image = new Image();<br/>    image.src = canvas.toDataURL("image/png");    <br/>    return image;<br/>}</p>

4、保存和恢复上下文

save方法用于保存上下文环境,restore方法用于恢复到上一次保存的上下文环境。

ctx.save();

ctx.shadowOffsetX = 10;
ctx.shadowOffsetY = 10;
ctx.shadowBlur = 5;
ctx.shadowColor = "rgba(0, 0, 0, 0.5)";

ctx.fillStyle = "#CC0000";
ctx.fillRect(10, 10, 150, 150);

ctx.restore();

ctx.fillStyle = "#000000";
ctx.fillRect(180, 10, 150, 100);

 上面的代码一共绘制了两个矩形,前一个有阴影,后一个没有。

The above is the detailed content of Detailed introduction to HTML5 new label Canvas. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
H5: New Features and Capabilities for Web DevelopmentH5: New Features and Capabilities for Web DevelopmentApr 29, 2025 am 12:07 AM

H5 brings a number of new functions and capabilities, greatly improving the interactivity and development efficiency of web pages. 1. Semantic tags such as enhance SEO. 2. Multimedia support simplifies audio and video playback through and tags. 3. Canvas drawing provides dynamic graphics drawing tools. 4. Local storage simplifies data storage through localStorage and sessionStorage. 5. The geolocation API facilitates the development of location-based services.

H5: Key Improvements in HTML5H5: Key Improvements in HTML5Apr 28, 2025 am 12:26 AM

HTML5 brings five key improvements: 1. Semantic tags improve code clarity and SEO effects; 2. Multimedia support simplifies video and audio embedding; 3. Form enhancement simplifies verification; 4. Offline and local storage improves user experience; 5. Canvas and graphics functions enhance the visualization of web pages.

HTML5: The Standard and its Impact on Web DevelopmentHTML5: The Standard and its Impact on Web DevelopmentApr 27, 2025 am 12:12 AM

The core features of HTML5 include semantic tags, multimedia support, offline storage and local storage, and form enhancement. 1. Semantic tags such as, etc. to improve code readability and SEO effect. 2. Simplify multimedia embedding with labels. 3. Offline storage and local storage such as ApplicationCache and LocalStorage support network-free operation and data storage. 4. Form enhancement introduces new input types and verification properties to simplify processing and verification.

H5 Code Examples: Practical Applications and TutorialsH5 Code Examples: Practical Applications and TutorialsApr 25, 2025 am 12:10 AM

H5 provides a variety of new features and functions, greatly enhancing the capabilities of front-end development. 1. Multimedia support: embed media through and elements, no plug-ins are required. 2. Canvas: Use elements to dynamically render 2D graphics and animations. 3. Local storage: implement persistent data storage through localStorage and sessionStorage to improve user experience.

The Connection Between H5 and HTML5: Similarities and DifferencesThe Connection Between H5 and HTML5: Similarities and DifferencesApr 24, 2025 am 12:01 AM

H5 and HTML5 are different concepts: HTML5 is a version of HTML, containing new elements and APIs; H5 is a mobile application development framework based on HTML5. HTML5 parses and renders code through the browser, while H5 applications need to run containers and interact with native code through JavaScript.

The Building Blocks of H5 Code: Key Elements and Their PurposeThe Building Blocks of H5 Code: Key Elements and Their PurposeApr 23, 2025 am 12:09 AM

Key elements of HTML5 include,,,,,, etc., which are used to build modern web pages. 1. Define the head content, 2. Used to navigate the link, 3. Represent the content of independent articles, 4. Organize the page content, 5. Display the sidebar content, 6. Define the footer, these elements enhance the structure and functionality of the web page.

HTML5 and H5: Understanding the Common UsageHTML5 and H5: Understanding the Common UsageApr 22, 2025 am 12:01 AM

There is no difference between HTML5 and H5, which is the abbreviation of HTML5. 1.HTML5 is the fifth version of HTML, which enhances the multimedia and interactive functions of web pages. 2.H5 is often used to refer to HTML5-based mobile web pages or applications, and is suitable for various mobile devices.

HTML5: The Building Blocks of the Modern Web (H5)HTML5: The Building Blocks of the Modern Web (H5)Apr 21, 2025 am 12:05 AM

HTML5 is the latest version of the Hypertext Markup Language, standardized by W3C. HTML5 introduces new semantic tags, multimedia support and form enhancements, improving web structure, user experience and SEO effects. HTML5 introduces new semantic tags, such as, ,, etc., to make the web page structure clearer and the SEO effect better. HTML5 supports multimedia elements and no third-party plug-ins are required, improving user experience and loading speed. HTML5 enhances form functions and introduces new input types such as, etc., which improves user experience and form verification efficiency.

See all articles

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

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor