Home Web Front-end H5 Tutorial Learning the basics of canvas

Learning the basics of canvas

Jul 15, 2017 am 11:45 AM
canvas study

Canvas (canvas) is a new tag element in html5, used to define graphics, such as charts and other images. The tag is just a container for graphics, and a script (usually javascript) must be used to draw the graphics.

The difference between canvas and svg

##
canvas是HTML5提供的新元素<canvas>,而svg存在的历史要比canvas久远,已经有十几年了。svg并不是html5专有的标签,最初svg是用xml技术(超文本扩展语言,可以自定义标签或属性)描述二维图形的语言。

首先,从它们的功能上来讲,canvas可以看做是一个画布。其绘制出来的图形为标量图,因此,可以在canvas中引入jpg或png这类格式的图片,在实际开发中,大型的网络游戏都是用canvas画布做出来的,并且canvas的技术现在已经相当的成熟。
另外,我们喜欢用canvas来做一些统计用的图表,如柱状图曲线图或饼状图等。而svg,所绘制的图形为矢量图,所以其用法上受到了限制。因为只能绘制矢量图,所以svg中不能引入普通的图片,因为矢量图的不会失真的效果,在项目中我们会用来做一些动态的小图标。
但是由于其本质为矢量图,可以被无限放大而不会失真,这很适合被用来做地图,而百度地图就是用svg技术做出来的。

另外从技术发面来讲canvas里面绘制的图形不能被引擎抓取,如我们要让canvas里面的一个图片跟随鼠标事件:canvas.onmouseover=function(){}。而svg里面的图形可以被引擎抓取,支持事件的绑定。
另外canvas中我们绘制图形通常是通过JavaScript来实现,svg更多的是通过标签来来实现,如在svg中绘制正矩形形就要用<rect>,这里我们不能用属性style="width:XXX;height:XXX;"来定义。
我再来介绍一个svg的js库:TWO.JS。其中包含two.js和three.js前者用于绘制二维图形,后者用于绘制三维图形。TWO.JS可以支持三种格式,svg(默认)、canvas、和WEBGL。当然也可以在普通div中引入。

要从同一图形的一个<canvas>标记中移除元素,需要擦掉重新绘制;而svg很容易编辑,只要从其描述中移除元素即可。

以上是之前在别人博客中看到的,所以先引用过来,待之后熟练掌握canvas,svg再写自己的心得体会。

具体请参考
Copy after login
<br><br><strong><span style="font-family: 'Microsoft YaHei'; font-size: 14px;">1、基本语法</span></strong>
Copy after login
<canvas id="canvasMain" width="800" height="600" >您的浏览器不支持canvas</canvas>
Copy after login

当没有设置宽度和高度的时候,canvas会初始化宽度为300px和高度为150px;当浏览器不支持canvas标签的时候,会显示其中的文字。

在canvas坐标体系中,以左上角为坐标原点,向右为x轴正方向,向下为y轴正方向,如下图:

进行绘制需要获取canvas的上下文环境context,之后调用API进行图像绘制

var canvas = document.getElementById("canvasMain"),
    ctx = canvas.getContext("2d");
Copy after login

 替换内容是在不支持标签的浏览器中展示的。也可以通过检测getContext()方法的存在来判断是否支持(有些浏览器会为html规范之外的元素创建默认的html元素对象)

<span style="color: #000000;">var canvas = document.getElementById("canvasMain");
if(canvas.getContext("2d")) {
    var ctx = canvas.getContext("2d");
    // drawing code here
} else {
    // canvas-unsupported code here
}<br></span>
Copy after login

导出在元素上绘制的图像,接收一个参数,即图像的MIME类型格式。若绘制到画布上的图像来自不同域,该方法会报错

var canvas = document.getElementById("canvasMain");if(canvas.getContext) {//取得图像的数据URIvar imgURI = canvas.toDataURL('image/png');//显示图像var image =  document.createElement('img');
    image.src = imgURI;
    document.body.appendChild(image);        
}
Copy after login

2、2D上下文

  • 填充和描边

  填充:用指定的样式(颜色、渐变、图像)填充图形;描边:在图形的边缘画线   两个属性分别是fillStyle  strokeStyle,属性的值可以是字符串、渐变对象或模式对象

  • 绘制矩形

          

  绘制矩形方法:fillRect()  strokeRect()   clearRect()  参数依次为:矩形x坐标、y坐标、宽度、高度

var drawing = document.getElementById('drawing');if(drawing.getContext) {var context = drawing.getContext('2d');
    context.strokeStyle = 'rgba(0, 0, 255, 0.5)';//描边属性context.fillStyle = 'pink';//填充属性context.lineWidth = 3; //描边线条宽度context.lineCap = 'square';//线条末端形状(butt平头、round圆头、square方头)context.lineJoin = 'round';//线条相交的方式(round圆交、bevel斜交、miter斜接)context.fillRect(10, 10, 50, 50);//填充矩形context.fillStyle = 'green';
    context.fillRect(30, 30, 50, 50);
    context.strokeRect(100, 10, 50, 50);//描边矩形context.clearRect(40, 40, 15, 15);//清除画布上的矩形区域             }
Copy after login
  • 绘制路径

   

   closePath()绘制一条连接到路径起点的线条

   fill()填充路径    stroke()描边路径   clip()在路径上创建一个剪切区域

   isPointInPath(x,y)判断画布上的某一点是否位于路径上

var drawing = document.getElementById('drawing');if(drawing.getContext) {/*绘制路径*/var context = drawing.getContext('2d');
            context.strokeStyle = 'pink';
            context.beginPath();//开始绘制新路径//绘制外圆context.arc(100, 100, 99, 0, 2*Math.PI, false);//参数依次为圆心坐标x、y、半径、起始角度(用弧度表示)、结束角度、起始角度是否按逆时针方向计算(flase为顺时针)context.moveTo(194, 100);//将绘图游标移动到(x,y),不画线//绘制内圆context.arc(100, 100, 94, 0, 2*Math.PI, false);//绘制分针context.moveTo(100, 100);
            context.lineTo(100, 25);//从上一点开始绘制一条直线,到(x,y)为止//绘制时针context.moveTo(100, 100);
            context.lineTo(35, 100);//绘制文本context.font = 'bold 14px Arial';//表示文本样式、大小、字体context.textAlign = 'center';//文本对齐方式(start、end、left、right、center),建议用start、end代替left、rightcontext.textBaseline = 'middle';//文本的基线(top、hanging、middle、alphabetical、ideopgraphic、bottom)context.fillText('12', 100, 20);//描边路径            context.stroke();//额外练习context.moveTo(230, 10);//arcTo(x1,y1,x2,y2,radius):从上一点开始绘制一条弧线,到(x2,y2)为止,并以给定的半径穿过(x1,y1)context.arcTo(280, 60, 330, 10, 50);//bezierCurveTo(c1x,c1y,c2x,c2y,x,y):从上一点开始绘制一条曲线,到(x,y)为止,并以(c1x,c1y)(c2x,c2y)为控制点context.bezierCurveTo(210, 70, 290, 90, 300, 100);
            context.moveTo(320, 10);//quadraticCurveTo(cx,cy,x,y):从上一点开始绘制一条二次曲线,到(x,y)为止,并以(cx,cy)为控制点context.quadraticCurveTo(420, 100, 400, 10);//rect(x,y,width,height):从点(x,y)开始绘制矩形,此方法绘制的是矩形路径而不是独立的形状context.rect(450, 10, 50, 50);
            context.stroke();
}
Copy after login
  • 绘制文本

  fillText()绘制文本    strokeText()为文本描边    参数:文本字符串、x坐标、y坐标、可选的最大像素宽度

  • 变换

  

var drawing = document.getElementById('drawing');if(drawing.getContext) {            //变换var context = drawing.getContext('2d');
            context.strokeStyle = 'rgba(0, 0, 255, 0.5)';
            context.beginPath();
            context.arc(100, 100, 99, 0, 2*Math.PI, false);
            context.moveTo(194, 100);
            context.arc(100, 100, 94, 0, 2*Math.PI, false);//变换原点context.translate(100, 100);//将坐标原点移动到该点//旋转表针context.rotate(1);//围绕原点旋转图像angle弧度//绘制分针context.moveTo(0, 0);
            context.lineTo(0, -80);//绘制时针context.moveTo(0, 0);
            context.lineTo(-65, 0);
            context.stroke();

            context.rotate(-1);
            context.fillStyle = 'rgba(0, 0, 255, 0.5)';
            context.save();//保存上下文状态,只保存绘图上下文的设置和变换,不会保存绘图上下文的内容context.fillStyle = 'pink';
            context.translate(-100, -100);
            context.save();
            context.fillStyle = 'green';
            context.fillRect(220, 10, 50, 50);

            context.restore();//返回之前保存的设置context.fillRect(280, 10, 50, 50);

            context.restore();
            context.fillRect(340, 10, 50, 50);
}
Copy after login
  • 绘制图像

   

  drawImage()还可传入元素作为第一个参数,表示把另一个画布内容绘制到当前画布上。

  可能遇到的问题:drawImage()图片不显示在画布上,原因可能是你取图片的时候,此时图片还没有加载出来

window.onload = function(){var drawing = document.getElementById('drawing');if(drawing.getContext) {//图像var context = drawing.getContext('2d');var image = document.images[0];//参数依次表示为:图像元素、源图像x坐标、y坐标、目标的宽度、高度context.drawImage(image, 0, 0, 150, 250);//参数依次表示为:图像元素、源图像x坐标、y坐标、源图像宽度、高度、目标图像x坐标、y坐标、目标图像宽度、高度context.drawImage(image, 100, 300, 500, 600, 0, 0, 70, 80);
        }
};
Copy after login
  • 阴影、渐变、模式

  

   模式与渐变一样,都是从画布原点(0,0)开始的,将填充样式设置为模式对象,只表示在某个特定区域内显示重复的图像,而不是从某个位置开始绘制重复的图像。

   createPattern()第一个参数也可以是

window.onload = function(){var drawing = document.getElementById('drawing');if(drawing.getContext) {//阴影var context = drawing.getContext('2d');
            context.shadowColor = 'rgba(0, 0, 0, 0.5)';//阴影颜色,默认黑色context.shadowOffsetX = 5;//x轴方向的阴影偏移量,默认0context.shadowOffsetY = 5;//y轴方向的阴影偏移量,默认0context.shadowBlur = 4;//模糊的像素数,默认0context.fillStyle = 'rgba(0, 0, 255, 0.5)';
            context.fillRect(10, 10, 50, 50);
            context.fillStyle = 'pink';
            context.fillRect(30, 30, 50, 50);//渐变var gradient = context.createLinearGradient(100, 10, 130, 130);//创建线性渐变,返回CanvasGradient对象的实例。参数:起点x坐标、y坐标、终点x坐标、y坐标gradient.addColorStop(0, 'white');//指定色标,参数:色标位置(0到1之间的数字,0表示开始的颜色,1为结束的颜色)、css颜色值gradient.addColorStop(1, 'black');

            context.fillStyle = gradient;
            context.fillRect(100, 10, 50, 50);var createLinearGradient = function(context, x, y, width, height) {return context.createLinearGradient(x, y, x+width, y+height);
            };var gradientNew = createLinearGradient(context, 180, 10, 50, 50);
            gradientNew.addColorStop(0, 'red');
            gradientNew.addColorStop(1, 'green');
            context.fillStyle = gradientNew;
            context.fillRect(180, 10, 50, 50);var gradientRound = context.createRadialGradient(275, 35, 10, 275, 35, 30);//径向渐变,参数:起点圆的圆心、半径,终点圆的圆心、半径gradientRound.addColorStop(0, 'pink');
            gradientRound.addColorStop(1, 'blue');
            context.fillStyle = gradientRound;
            context.fillRect(250, 10, 50, 50);//模式,即重复的图像,可以用来填充或描边图形var image = document.images[0],
                pattern = context.createPattern(image, 'repeat-x');//创建新模式,参数:图像元素、是否重复(repeat、repeat-x、repeat-y、no-repeat)context.fillStyle = pattern;
            context.fillRect(350, 10, 350, 350);
        }
}
Copy after login
  • Using image data

GetImageData() can obtain the original image data, parameter: x coordinate of the screen area where the data is to be obtained , y coordinate, width, height. The returned object is an instance of ImageData, which has three properties: width, height, and data. Data is an array, which stores the data of each pixel in the image. Each pixel is represented by 4 elements, representing red, green, blue and transparency values ​​respectively. Therefore, the data of the first pixel is saved in the 0th to 3rd elements of the array.

Note: Image data can only be obtained if the canvas is "clean" (that is, the image does not come from other domains).

  • Synthesis

 

globalAlpha: A value between 0 and 1 (inclusive 0 and 1), used to specify transparency, the default is 0.
globalCompositionOperation: Indicates how the graphics drawn later are combined with the graphics drawn first.

 

 

3、WebGL

 

WebGL is for canvas 3D context is not a standard developed by W3C.

Canvas is an important new feature of H5, and everyone needs to spend some effort to learn and use it.

The above is the detailed content of Learning the basics of canvas. For more information, please follow other related articles on the PHP Chinese website!

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)

Revealing the appeal of C language: Uncovering the potential of programmers Revealing the appeal of C language: Uncovering the potential of programmers Feb 24, 2024 pm 11:21 PM

The Charm of Learning C Language: Unlocking the Potential of Programmers With the continuous development of technology, computer programming has become a field that has attracted much attention. Among many programming languages, C language has always been loved by programmers. Its simplicity, efficiency and wide application make learning C language the first step for many people to enter the field of programming. This article will discuss the charm of learning C language and how to unlock the potential of programmers by learning C language. First of all, the charm of learning C language lies in its simplicity. Compared with other programming languages, C language

Getting Started with Pygame: Comprehensive Installation and Configuration Tutorial Getting Started with Pygame: Comprehensive Installation and Configuration Tutorial Feb 19, 2024 pm 10:10 PM

Learn Pygame from scratch: complete installation and configuration tutorial, specific code examples required Introduction: Pygame is an open source game development library developed using the Python programming language. It provides a wealth of functions and tools, allowing developers to easily create a variety of type of game. This article will help you learn Pygame from scratch, and provide a complete installation and configuration tutorial, as well as specific code examples to get you started quickly. Part One: Installing Python and Pygame First, make sure you have

Let's learn how to input the root number in Word together Let's learn how to input the root number in Word together Mar 19, 2024 pm 08:52 PM

When editing text content in Word, you sometimes need to enter formula symbols. Some guys don’t know how to input the root number in Word, so Xiaomian asked me to share with my friends a tutorial on how to input the root number in Word. Hope it helps my friends. First, open the Word software on your computer, then open the file you want to edit, and move the cursor to the location where you need to insert the root sign, refer to the picture example below. 2. Select [Insert], and then select [Formula] in the symbol. As shown in the red circle in the picture below: 3. Then select [Insert New Formula] below. As shown in the red circle in the picture below: 4. Select [Radical Formula], and then select the appropriate root sign. As shown in the red circle in the picture below:

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

Learn the main function in Go language from scratch Learn the main function in Go language from scratch Mar 27, 2024 pm 05:03 PM

Title: Learn the main function in Go language from scratch. As a simple and efficient programming language, Go language is favored by developers. In the Go language, the main function is an entry function, and every Go program must contain the main function as the entry point of the program. This article will introduce how to learn the main function in Go language from scratch and provide specific code examples. 1. First, we need to install the Go language development environment. You can go to the official website (https://golang.org

Explore the powerful role and application of canvas in game development Explore the powerful role and application of canvas in game development Jan 17, 2024 am 11:00 AM

Understand the power and application of canvas in game development Overview: With the rapid development of Internet technology, web games are becoming more and more popular among players. As an important part of web game development, canvas technology has gradually emerged in game development, showing its powerful power and application. This article will introduce the potential of canvas in game development and demonstrate its application through specific code examples. 1. Introduction to canvas technology Canvas is a new element in HTML5, which allows us to use

Understand these 20 Dune analysis dashboards and quickly capture trends on the chain Understand these 20 Dune analysis dashboards and quickly capture trends on the chain Mar 13, 2024 am 09:19 AM

Original author: Minty, encryption KOL Original compilation: Shenchao TechFlow If you know how to use it, Dune is an all-in-one alpha tool. Take your research to the next level with these 20 Dune dashboards. 1. TopHolder Analysis This simple tool developed by @dcfpascal can analyze tokens based on indicators such as holders’ monthly activity, number of unique holders, and wallet profit and loss ratio. Visit link: https://dune.com/dcfpascal/token-holders2. Token Overview Metrics @andrewhong5297 created this dashboard which provides a way to evaluate tokens by analyzing user actions

The development trend and future prospects of Canvas in China's education sector The development trend and future prospects of Canvas in China's education sector Jan 17, 2024 am 10:22 AM

With the rapid development of science and technology and the widespread application of information technology in the field of education, Canvas, as a world-leading online learning management system, is gradually emerging in the Chinese education industry. The emergence of Canvas provides new possibilities for the reform of education and teaching methods in China. This article will explore the development trends and prospects of Canvas in China’s education sector. First of all, one of the development trends of Canvas in China’s education sector is in-depth integration. With the rapid development of cloud computing, big data and artificial intelligence, Canvas will increasingly

See all articles