H5 notes --- five front-end, javascript base + canvas canvas

If someone asks me what your dreams are, I would say: "Affordable something you like, do what you love to do, to say the field trip with their parents to stay away to make another one wedding, one belongs to. their travel. If you like people who like themselves, it was perfect, if not appropriate, it will not result in the loss of quality of life, but because of their own money to spend, become more emboldened, this may be the effort the reasons for it. "

We have QQ, did not receive a red envelope drawing it, Here Insert Picture Description
** you know how to do it? ** Let us learn the new features canvas H5 with it

First the canvas before learning to master the basics of javascript

● JavaScript introduction

● introduction of JavaScript files and CSS files similar method introduced in an HTML document, divided into two ways:

Here Insert Picture Description

● Data Types

● JavaScript There are five basic types of data.

Here Insert Picture Description
● Tag

● using var in JavaScript are declared local variables.

var str="变量名";
var num=1.5;
age=23;
var str=new String;
var cars=new Array("A","B","C);//数组

In JavaScript, "new new" keyword is used to declare variables, all variables are objects, declare a variable, you create a new object.

● Function

● function (function) method also called, is - - some code organized together to form a block for performing a particular function call may be repeated when needed.

Here Insert Picture Description
● Objects

● In JavaScript, the object is to have the properties and methods of data. Property values ​​are related to the object, the object is an operation that can be performed.

Here Insert Picture Description
● event processing

● event-driven is a fundamental feature of the JavaScript language, so-called event refers to an operation performed by a user when visiting a page, commonly used event types shown in the table at right.

Here Insert Picture Description

● event processing

● Further events have many attributes, attributes common event in the table below.

Here Insert Picture Description

●JavaScript HTML DOM

● DOM is called the Document Object Model (Document Object Model). When the page is loaded, the browser will HTMLDOM model is constructed as an object tree.

Here Insert Picture Description

● to create dynamic HTML using JavaScript. Mainly in four aspects.

Here Insert Picture Description

● Method To manipulate HTML elements and attributes, this element should first be obtained. Objects, common object acquired HTML document element objects in the table below.

Here Insert Picture Description
● getBoundingClientRect () method
a getBoundingClientRect () method is used to obtain an element of a page left, top, right and bottom, respectively, the relative position of the browser window, or the coordinates of a Element element is now a W3C standard.
- This method returns an Object Interview object has six attributes: top, left, right, bottom , width, height, the specific application as shown below.
Here Insert Picture Description

Acquaintance canvas

canvas canvas means in real life is a canvas for painting, HTML5 in canvas Similarly, we can call it "webpage canvas" With this canvas can easily draw graphics on the page, the text and pictures.
● Creating the Canvas

● HTML5 provides a label, the label can be created using the canvas in a rectangular area of ​​the page.

Here Insert Picture Description
Canvas itself does not have the drawing function, through a scripting language - draw operations (like as JavaScript) API operation to draw graphics. You can use getElementByld () method to get the canvas object:
Here Insert Picture Description
● prepare brush

● Once you have the canvas to start painting need to prepare - - only brush, this brush is the context object, which can be obtained using a JavaScript script.

Here Insert Picture Description
● coordinate and starting point

● Next you need to set the context of the beginning of the plotted points, that is, "Where do you start painting."

Here Insert Picture Description
● Draw a line

● lineTo () method is used to define the drawing from the position "x, y" - A straight line or a thread to the start point.

Here Insert Picture Description
● Path

● After drawing a straight line to determine the starting point and the point of the thread, they formed - to draw a path bar, if you must use a complex path to draw the path begins and ends.

Here Insert Picture Description
● stroke and fill

● the canvas graphics rendering, the path is only a draft, the real draw line must perform stroke () method according to the stroke path, it may also be used fill () method to fill pattern.

Here Insert Picture Description

The basic steps used to draw graphics canvas:
A) creating a canvas: <canvas> </ canvas>
B) Preparation brush (acquired context object): canvas.getContext ( '2D');
C) Start route planning: context.beginPath () ;
D) moving start point: context.moveTo (X, Y);
E) line is drawn (rectangular, circular, pictures ...): context.lineTo (X, Y);
F) closed path: context.closePath ();
g) draw stroke: context.stroke ();

Case: Web Scribble
Effect: This art work is too low, we will look at the
Here Insert Picture Description
idea

① The graffiti to be displayed in the middle of the screen plate, so <canvas> tag can be nested in the <center> tag.
② write JavaScript code, first create a canvas, ready to brush and thick canvas and set the width and height of the border; then move the mouse pointer as brushes, is triggered when the mouse down onmousedown event, use the moveTo () method to determine the starting point, when the mouse lineTo scribed using mobile onmousemove trigger event.
③ acquired mouse x, Y-coordinate is very simple, and can be used clientX clientY to obtain, when the mouse acts on an object, such as canvas, is necessary to consider the position of the object in the browser window, then the method will be used getBoundingClientRect0 to get the canvas rectangle object, and use the mouse coordinates subtracted from the upper left corner of this rectangle object to the browser.

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>CANVAS画布</title>
</head>
<body>
	<center>
		<canvas id="cavsElem">
			您的浏览器不支持canvas,请升级浏览器
		</canvas>
	</center>
	
	<script type="text/javascript">
		// 当前立即执行function
		(function(){
			// 初始化画布
			var canvas =document.getElementById('cavsElem');
			canvas.width= 900;
			canvas.height=600;
			canvas.style.border='1px solid #000';
			// 拿到画布对象
			var context=canvas.getContext('2d');

			// 在鼠标按下的时候开始绘制线条
			canvas.onmousedown =function(e){

				// 绘制直线的开始位置
				// alert(e.clientX+""+e.clientY);
				
				// 需要知道画布原点的坐标
				var pos =canvas.getBoundingClientRect();
				// alert(pos.left+""+ pos.top);

				// 需要知道距离画布原点的坐标
				// alert((e.clientX-pos.left)+":"+(e.clientY-pos.top));

				context.beginPath();
				context.moveTo((e.clientX-pos.left),(e.clientY-pos.top));

				// 监听鼠标移动的事件
				canvas.onmousemove= function(e){
					console.log((e.clientX-pos.left),(e.clientY-pos.top));

					// 不停地绘制线条
				context.lineTo((e.clientX-pos.left),(e.clientY-pos.top));
				// context.closePath();
				context.stroke();
				}
				canvas.onmouseup =function(){
					canvas.onmousemove =null;
				}
			}

		});

	</script>
</body>
</html>

Clear rectangular canvas and draw a rectangle

  • It was used in the strokeRect canvas () and the fillRect () method to draw a filled rectangle and rectangular border.

context.strokeRect(x,y,width,height);
context.fillRect(x,y,width,height);

There is also a method of the canvas to an eraser, and use it to clear the contents of the rectangle drawn.

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

canvas using ARC () method to draw arcs and circles.

context.arc (X, Y, RADIUS, startAngle, endAngle, bAntiClockwise);
X, Y: center point radius: length of the radius startAngle: Start radians endAngle: End radians bAntiClockwise: whether counterclockwise (false: clockwise, true: counterclockwise )

canvas draw pictures

● Draw pictures canvas in fact, put a picture on the canvas.

// Draw picture
context.drawlmage (Image, DX, Dy))
// not to scale drawing
context.drawlmage (Image, DX, Dy, DWIDTH, dHeight)
// slice drawing
context.drawlmage (image, sx, Sy, sWidth, sHeigh, dx, dy, DWIDTH, dHeight)
----- Image: source ----- dx, dy: coordinate ----- dWidth targets, dHeight: width and height of the target ---- -sx, sy: image start coordinates in the source ----- SWidth, sHeight: the source image width and height

canvas Other methods

● related graphics drawing method of the canvas provided, there are many, followed by introduction of several methods related to the project, as follows.

Here Insert Picture Description
Case: red envelopes can see photos
Here Insert Picture Description
Description: When I click to see: the circle randomly selected area on the canvas, you can only see a little bit of content, when you click receive a red envelope can see the complete picture, which species are commonly used in the marketing method.

Ideas :

Red envelopes can see photos
① using <a> tag to do two buttons, and set the style for the button.
② picture blur effect using the CSS filter "fiter: blur (px)" to achieve, the property can be achieved myopia forgot to wear glasses to see things blur
③ positioning of each element are the <div> tag relative positioning, need Note that the two buttons to be displayed in the uppermost layer, Z-index maximum value can be set to 999, followed by <canvas> tag, and finally the <img> tag, the circular portion can be displayed using a circular canvas to be implemented of.
The CSS the HTML + 2:
① draw a circle: setRegion (Region), which requires the use of Clip () method of cutting a circular area, and then draw a circle in the picture area, the effect is circular in Figure 5-24 it .
② draw pictures: the draw (image) method needs to call setRegion (Region) method, and use dlearRect () method to clear - - time to draw a circle, to ensure that only display a circular area.
③ Initial Canvas: initCanvas () method call draw (image) method.
④ "I want to see it" button click event reset () method is called initCanvas () method In this method, each time drawing a circular area in a different location.
⑤ "received a red envelope" button click event show () method, called the method draw (image) method, the circular radius is larger than the canvas, then you can draw a complete picture, that is, to receive a red envelope effect .

html code:

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>发红包</title>
	<link rel="stylesheet" type="text/css" href="css/photo.css"/>
</head>
<body>
	<div class="blurDiv">
		<img class="blurImg" src="pic.jpg" alt="#"/>
		<canvas id="mycanvas"></canvas>
		<a class="button" id="buttonreset" href="javascript:reset()">想看我</a>
		<a class="button" href="javascript:show()" id="buttonshow"> 收到红包</a>
	</div>
	<script type="text/javascript" src="js/photo.js"></script>
</body>
</html>

css code:

.body{
	margin: 0;
	padding: 0;
}
.blurDiv{
	position: relative;
	width: 877px;
	height: 672px;
	margin:50px auto 0px;/*定义外边距:顶部50px,左右水平居中,距离底部0px*/
}
.blurDiv .blurImg{
	width: 877px;
	height: 672px;
	display: block;/*把行元素强制转换为块级元素*/
	filter: blur(20px);/*滤镜,设置模糊度*/
	-webkit-filter:blur(20px);/*webkit保留filter*/
	position: absolute;
	left: 0;
	top: 0;
	z-index: 0;
}
.blurDiv #mycanvas{
	position: absolute;
	top: 0;
	left: 0;
	z-index: 99;
}

/*按钮*/
.blurDiv .button{
	display: block;
	width: 240px;
	height: 60px;
	border-radius: 5px;
	line-height: 60px;
	text-align: center;
	position: absolute;
	top: 105%;
	font-family: arial;
	font-size: 1.5em;/*相当于24px*/
	color: #fff;
	text-decoration: none;/*清除字体样式*/
	z-index:999;
}
.blurDiv #buttonreset{
	left: 7%;
	background-color: #c85814;
}
.blurDiv #buttonreset:hover{
	background-color: #ffb151;
}
.blurDiv #buttonshow{
	right:7%;
	background-color: #ff2f2e;
}
.blurDiv #buttonshow:hover{
	background-color: #ff596b;
}

js code:

var canvasWidth =877;//声明画布的宽度
var canvasHeight =672;

var canvas = document.getElementById('mycanvas');
var context =canvas.getContext('2d');

canvas.width=canvasWidth;
canvas.height=canvasHeight;

var image = new Image();
image.src='pic.jpg';
image.οnlοad=function(){
	initCanvas();/*注:*/
}
var radius=50;

function initCanvas(){
	Region = {
		x:Math.random()*(canvasWidth-2*radius)+radius,
		y:Math.random()*(canvasHeight-2*radius)+radius,
		r:radius
	};
	draw();
}

function setRegion(){
	context.beginPath();
	context.arc(Region.x,Region.y,Region.r,2*Math.PI,false);
	context.clip();
}

function draw(){
	context.clearRect(0,0,canvas.width,canvas.height);
	context.save();
	setRegion();
	context.drawImage(image,0,0);
	context.restore();
}

// 单击事件reset方法,在该方法调用initCanvas()方法,每一次在不同的位置绘制圆形区域
function reset(){
	initCanvas();
}

function show(){
	Region.r=2*Math.max(canvas.width,canvas.height);
	draw();
}
Published 18 original articles · won praise 20 · views 2394

Guess you like

Origin blog.csdn.net/qq_43009710/article/details/105214268