1.持久化
三种持久化方式: cookie\local storage\session storage
前后端分别操作cookie
01_cookie.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>cookie</title>
</head>
<body>
<button>点击添加cookie</button>
<script>
// 1.前端操作cookie
/*
数据持久化:
1.cookie
2.local storage
3.session storage
*/
// 1000s后, 前端时间戳必须转为标准时
// var expires = new Date(new Date().getTime() + 1000*1000).toGMTString();
// 添加cookie
// document.cookie = 'username=frank;expires=' + expires;
// console.log(document.cookie);
// cookie转对象
/* var tempArr = document.cookie.split("=");
var tempObj = {};
tempObj[tempArr[0]] = tempArr[1];
console.log(tempObj);*/
// 2.后端操作cookie
document.querySelector('button').onclick = function () {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if(xhr.readyState == 4) {
if(xhr.status == 200) {
console.log(xhr.responseText);
}
}
};
xhr.open('post', '01_cookie.php', true);
var formData = new FormData();
formData.append('username', 'frank');
xhr.send(formData);
};
</script>
</body>
</html>
01_cookie.php
<?php
$username = $_POST['username'];
// 后端操作cookie
// 1000s后过期
// 设置cookie
// setcookie('username', $username, time() + 1000);
// 读取cookie
// echo json_encode($_COOKIE);
// 删除cookie
// setcookie('username', '', time()+1);
$success = array('msg'=>'ok', 'info'=>$_POST);
echo json_encode($success);
操作多个cookie及复杂cookie处理
02_cookie_demo.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>cookie补充</title>
</head>
<body>
<button>读取本地cookie</button>
<script>
// 1.请求后台设置多个cookie
/* (function () {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if(xhr.readyState == 4) {
if(xhr.status == 200) {
console.log(xhr.responseText);
}
}
};
var formData = new FormData();
formData.append('nickname', 'frank');
formData.append('userid', '10000');
xhr.open('post', '02_cookie_demo.php', true);
xhr.send(formData);
})();*/
// 2.读取多个cookie
document.querySelector('button').onclick = function () {
var cookie = document.cookie;
var cookieArr = cookie.split(';');
var objArr = [];
for(var i=0; i< cookieArr.length; i++) {
var obj = {};
var tempArr = cookieArr[i].trim().split('=');
obj[tempArr[0]] = tempArr[1];
objArr.push(obj);
}
console.log(objArr);
console.log(JSON.parse(objArr[2].userInfo));
}
// 3.存储内容为非字符串的复杂结构时
var info = {
uname: 'frank',
age: 18,
gender: 'male'
};
var cookieStr = JSON.stringify(info);
console.log(cookieStr);
var expires = new Date(new Date().getTime() + 1000*1000).toGMTString();
document.cookie = 'userInfo=' + cookieStr + ';expires=' + expires;
</script>
</body>
</html>
02_cookie_demo.php
<?php
// 1.设置多个cookie
/* $nickname = $_POST['nickname'];
$userid = $_POST['userid'];
setcookie('nickname', $nickname, time() + 3600*24);
setcookie('userid', userid, time() + 3600*24);*/
$info = array('uname' => 'frank', 'age' => 18, 'gender' => 'male');
$success = array('msg' => 'ok', 'info' => $info);
echo json_encode($success);
案例
03_cookie_demo.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.loginRegistDiv{
text-align: center; padding: 15px;
border: 1px solid black; width:300px; min-height:30px;
}
.welcomeDiv{
text-align: center; padding: 15px;
border: 1px solid black; width: 300px; min-height:30px; display: none;
}
.nickNameSpan{
color: green; font-size: 22px; font-weight: bold;
}
</style>
</head>
<body>
<div class="loginRegistDiv">
<label for="userName">
<span>用户名:</span><input type="text" id="userName" placeholder='请输入用户名'>
</label><br/>
<label for="password">
<span>密 码:</span><input type="text" id="password" placeholder='请输入密码'>
</label><br/><br/>
<button class="loginBtn">登录</button>
<button class="registBtn">注册</button>
</div>
<div class="welcomeDiv">
欢迎回来,尊敬的:
<span class='nickNameSpan'>哈哈哈</span>
<br/><br/>
<button class="exitBtn">注销登录</button>
</div>
<script>
;(function () {
var loginBtn = document.querySelector('.loginBtn');
var exitBtn = document.querySelector('.exitBtn');
var userNameInput = document.querySelector('#userName');
var passwordInput = document.querySelector('#password');
var welcomeDiv = document.querySelector('.welcomeDiv');
var loginRegistDiv = document.querySelector('.loginRegistDiv');
var nickNameSpan = document.querySelector('.nickNameSpan');
// 进入页面先读cookie
function getCookie() {
var cookie = document.cookie;
var cookieArr = cookie.split(';');
var obj = {};
for(var i=0; i< cookieArr.length; i++) {
var obj = {};
var tempArr = cookieArr[i].trim().split('=');
obj[tempArr[0]] = tempArr[1];
}
return obj;
}
var cookieObj = getCookie();
if(cookieObj.nickname != undefined &&cookieObj.nickname.length != 0) {
welcomeDiv.style.display = 'block';
loginRegistDiv.style.display = 'none';
nickNameSpan.innerHTML = cookieObj.nickname;
}
loginBtn.onclick = function () {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if(xhr.readyState == 4) {
if(xhr.status == 200) {
var dataObj = JSON.parse(xhr.responseText);
if(dataObj.statusCode == 1) {
welcomeDiv.style.display = 'block';
loginRegistDiv.style.display = 'none';
nickNameSpan.innerHTML = dataObj.nickname;
}
}
}
};
xhr.open('post', '03_cookie_demo.php', true);
var formData = new FormData();
formData.append('uname', userNameInput.value);
formData.append('upass', passwordInput.value);
xhr.send(formData);
}
exitBtn.onclick = function () {
userNameInput.value = '';
passwordInput.value = '';
welcomeDiv.style.display = 'none';
loginRegistDiv.style.display = 'block';
var expires = new Date(new Date().getTime() + 1).toGMTString();
document.cookie = 'nickname=frank;expires=' + expires;
}
})();
</script>
</body>
</html>
03_cookie_demo.php
<?php
$success = array('msg' => 'ok');
$username = $_POST['uname'];
$password = $_POST['upass'];
// 添加cookie
setcookie('nickname', 'frank', time()+3600*24);
$success['statusCode'] = 1;
$success['nickname'] = 'frank';
echo json_encode($success);
localstorage sessionstorage
04_storage.html
<html lang="en">
<head>
<meta charset="UTF-8">
<title>localStorage与sessionStorage</title>
</head>
<body>
<button class="addCookieBtn">点击添加cookie</button>
<button class="localStorage">local存储</button>
<button class="sessionStorage">session存储</button>
<script>
/*
* localstorage用户不主动删除即永远存在
* sessionstorage浏览器关闭自动删除
*/
/* document.querySelector('.localStorage').onclick = function () {
// 设置localStorage
localStorage.setItem('nickname', 'vincent');
}*/
// localStorage读取
/* var nickname = localStorage.getItem('nickname');
console.log(nickname);*/
/* document.querySelector('.sessionStorage').onclick = function () {
// 设置sessionStorage
sessionStorage.setItem('userid', '123123123');
}*/
// 页面关闭后消失
/* var userid = sessionStorage.getItem('userid');
console.log(userid);*/
;(function () {
var addCookieBtn = document.querySelector('.addCookieBtn');
addCookieBtn.onclick = function () {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if(xhr.readyState == 4) {
if(xhr.status == 200) {
console.log(xhr.responseText);
}
}
};
xhr.open('get', '04_storage.php', true);
xhr.send(null);
}
})();
</script>
</body>
</html>
04_storage.php
<?php
$success = array('msg' => 'ok');
// path默认为当前页面的上一级目录
setcookie('username', 'vincent', time()+3600*24, '/');
echo json_encode($success);
4.webWorker
web内容在后台运行脚本
异步操作都有回调
05_webworker.js
setTimeout(function () {
// 触发外部执行
postMessage('hello world');
},5000);
05_webworker.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<button>开启webworker</button>
<script>
/*无需引入webworker的js*/
var num = 1;
var timer = null;
// 前台执行
timer = setInterval(function () {
console.log(num++);
}, 1000);
// webworker后台执行
document.querySelector('button').onclick = function () {
var worker = new Worker('js/05_webworker.js');
worker.onmessage = function (event) {
// postMessage传回的数据
console.log(event.data);
};
};
</script>
</body>
</html>
5.FileReader
对文件进行预览
三种读写方式:
文本 \ 图片url \ 二进制流
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.showDiv{
width: 300px; min-height: 50px; border: 1px solid black; padding: 10px; margin-top: 10px;
}
img{ width: 300px; }
</style>
</head>
<body>
<input type="file" class="file" multiple>
<button>上传文件</button>
<div class="showDiv"></div>
<img src="">
<script>
var fileInput = document.querySelector('.file');
var btn = document.querySelector('button');
var showDiv = document.querySelector('.showDiv');
var img = document.querySelector('img');
btn.onclick = function () {
// 1.图片读取
/* var filereader = new FileReader();
filereader.readAsText(fileInput.files[0]);
filereader.onload = function () {
showDiv.innerHTML = filereader.result;
};*/
var filereader = new FileReader();
filereader.readAsDataURL(fileInput.files[0]);
filereader.onload = function () {
// TODO 乱码
img.src = filereader.result;
};
};
</script>
</body>
</html>
6.获取用户多媒体设备
window.navigator提供的getUserMedia方法,通常与canvas标签配合
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>多媒体</title>
<style>
#myvideo{
width: 250px;
height: 200px;
border: 1px solid #000;
}
</style>
</head>
<body>
<video src="" id="myvideo"></video>
<button class="playVideo">开启视频</button>
<canvas id="mycanvas"></canvas>
<img src="">
<button id="openVideo">视频</button>
<button id="snapshot">截图</button>
</body>
<script>
var video = document.getElementById('myvideo');
var canvas = document.querySelector('#mycanvas');
var bicaso = canvas.getContext('2d');
// var img = document.querySelector('img');
var playVideo = document.querySelector('.playVideo');
// TODO 播放失败
playVideo.onclick = function () {
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
navigator.getUserMedia({
// 开摄像头
video: true,
// 开麦克风
audio: true
}, function (stream) {
// 摄像头设备捕捉到的信息实时加载到video标签
// 兼容
var URL = window.URL || window.webkitURL;
video.src = URL.createObjectURL(stream);
// 播放
video.play();
}, function (err) {
console.log(err);
});
};
document.querySelector('#snapshot').onclick = function (){
if (mediaStream) {
bicaso.drawImage(video, 0, 0, 250, 200);
document.querySelector('img').src = canvas.toDataURL('image/webp');
//
}
};
</script>
</body>
</html>
7.canvas
目的是替代flash等用于做动画或游戏的插件,减小页面的结构大小
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>canvas</title>
<style>
.canvas{
border: 1px solid black;
}
</style>
</head>
<body>
<canvas width="300" height="200" class="canvas">
您的浏览器不支持canvas,请更换
</canvas>
<script>
/*
* canvas可以理解为一个div,提供一个绘制图形的区域(画板)
* 习惯在便签内部设置大小,而非css或js
* 通常加一句兼容提示
* canvas内部所有内容或图形使用js完成
* 上屏即像素化
*/
var huaban = document.querySelector('.canvas');
// canvas上下文对象
var bicaso = huaban.getContext('2d');
// console.log(bicaso);
// 填充矩形
// bicaso.fillRect(10, 10, 50, 50);
// 描边矩形
// bicaso.strokeRect(10, 10, 50, 50);
// 1.canvas上屏即像素化
// 画笔颜色
bicaso.fillStyle = 'purple';
// bicaso.fillRect(10, 50, 50, 50);
// 图形移动需要擦除后重绘
var x = 10;
// 图形行进方向,正右负左
var direction = 1;
setInterval(function () {
// 擦除原图
bicaso.clearRect(0, 0, 300, 200);
// 折返运动
if(x == 0) {
direction = 1;
}
if(x == 250) {
direction = -1;
}
switch(direction) {
case 1:
bicaso.fillRect(x++, 50, 50, 50);
break;
case -1:
bicaso.fillRect(x--, 50, 50, 50);
break;
}
}, 2);
// 2.fps 每秒帧数
</script>
</body>
</html>
矩形与路径绘制
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>矩形与路径绘制</title>
<style>
.canvas{
border: 1px solid black;
}
</style>
</head>
<body>
<canvas width="300" height="200" class="canvas">
您的浏览器不支持canvas,请更换
</canvas>
<script>
var huaban = document.querySelector('.canvas');
var bicaso = huaban.getContext('2d');
// 1.矩形绘制
/* // 填充
bicaso.fillRect(10, 10, 50, 50);
// 描边
bicaso.strokeRect(80, 80, 50, 50);
// 擦除
bicaso.clearRect(75, 70, 50, 50);*/
// 2.路径绘制
// 笔触颜色
/* bicaso.strokeStyle = 'skyblue';
// 落笔点坐标
bicaso.moveTo(70, 70);
// 笔触路径
bicaso.lineTo(10, 10);
// 绘制
bicaso.stroke();*/
// 填充颜色
/* bicaso.fillStyle = 'skyblue';
bicaso.fillRect(10, 10, 50, 50);*/
// 开始绘制
// bicaso.beginPath();
// ...绘制不受其他图形影响
// 结束绘制
// bicaso.closePath();
</script>
</body>
</html>
圆形及线型绘制
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>圆形</title>
<style>
.canvas{
border: 1px solid black;
}
</style>
</head>
<body>
<canvas width="300" height="200" class="canvas">
您的浏览器不支持canvas,请更换
</canvas>
<script>
var huaban = document.querySelector('.canvas');
var bicaso = huaban.getContext('2d');
// 1.圆形绘制
/* // 坐标x 坐标y 半径 开始弧度 结束弧度 顺时针
bicaso.arc(100, 100, 50, 0, 0.5*Math.PI, true);
bicaso.stroke();
// bicaso.fill();*/
// 2.线型绘制
bicaso.beginPath();
// 线宽
// bicaso.lineWidth = 20;
// bicaso.setLineDash([10, 30]);
bicaso.setLineDash([10, 5, 20]);
// 圆角端点
// bicaso.lineCap = 'round';
// 方块端点
// bicaso.lineCap = 'square';
// 圆弧连接
// bicaso.lineJoin = 'round';
// 截面连接
// bicaso.lineJoin = 'bevel';
bicaso.moveTo(40, 80);
bicaso.lineTo(230, 80);
bicaso.lineTo(230, 180);
bicaso.stroke();
bicaso.closePath();
</script>
</body>
</html>
图片加载和underscore
upderscore.js提供一系列便捷工具类
文档:
https://www.html.cn/doc/underscore/
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>图片加载</title>
<style>
.canvas{
border: 1px solid black;
}
</style>
</head>
<body>
<canvas width="1300" height="1200" class="canvas">
您的浏览器不支持canvas,请更换
</canvas>
<script src="js/underscore.js"></script>
<script>
var huaban = document.querySelector('.canvas');
var bicaso = huaban.getContext('2d');
// 1.绘制图片
/* bicaso.beginPath();
var tempImg = new Image();
tempImg.src = 'img/frank.jpg';
// 等待图片加载完成
tempImg.onload = function () {
bicaso.drawImage(tempImg, 10, 10);
// 宽高
// bicaso.drawImage(tempImg, 10, 10, 100, 100);
// 裁切绘制
// bicaso.drawImage(tempImg, 10, 10, 10, 10, 10, 10, 10, 10);
};
bicaso.closePath();*/
// 2.upderscore.js
/* var arr = ['a', 'b', 'c', 'd', 'e'];
var obj = {
name: 'vincent',
name: 'frank'
}
// 相当于for循环
_.each(obj, function (element, index, list) {
console.log(element);
console.log(index);
console.log(list);
})*/
/* var arr = [1, 2, 3, 4];
// 获取数组最大值
var max = _.max(arr);
console.log(max);*/
// 获取min到max的随机整数
/* var random = _.random(0, 10);
console.log(random);*/
// 删除数组元素
/* var arr = _.without([1, 2, 3, 4, 5], 0, 1);
console.log(arr);*/
</script>
</body>
</html>
案例-粒子效果
<html lang="en">
<head>
<meta charset="UTF-8">
<title>粒子效果</title>
<style>
*{ margin: 0; padding: 0; }
.canvas{ border: 1px solid black; background: black; }
</style>
</head>
<body>
<canvas width="320" height="500" class="canvas">
您的浏览器不支持canvas,请更换
</canvas>
<script src="js/underscore.js"></script>
<script>
var huaban = document.querySelector('.canvas');
var bicaso = huaban.getContext('2d');
var ballArr = [];
// 鼠标移动事件
huaban.onmousemove = function (event) {
new Ball(event.offsetX, event.offsetY);
};
// 20ms刷新一次
setInterval(function () {
// 清屏
bicaso.clearRect(0, 0, 320, 500);
// 绘制所有小球
_.each(ballArr, function (element) {
// 变更小球的位置
element.update();
element.render();
})
}, 20);
// 球类
function Ball(x, y) {
this.x = x;
this.y = y;
// 随机半径
this.r = _.random(5, 10);
// 随机颜色
this.c = _.sample(['red', 'orange', 'pink', 'green', 'yellow']);
// 随机位移
this.dx = _.random(-4, 4);
this.dy = _.random(-4, 4);
ballArr.push(this);
}
// 原型方法,所有对象公用
Ball.prototype.render = function () {
if(this.r <= 0) {
return;
} else {
bicaso.beginPath();
bicaso.arc(this.x, this.y, this.r, 0, 2*Math.PI);
bicaso.fillStyle = this.c;
bicaso.fill();
bicaso.closePath();
}
};
Ball.prototype.update = function () {
this.x += this.dx;
this.y += this.dy;
this.r -= 0.5;
// 当前半径小于0从数组中删除
if(this.r <= 0) {
_.without(ballArr, this);
}
}
</script>
</body>
</html>
8.百度地图sdk
http://lbsyun.baidu.com/index.php?title=jspopular/guide/getkey
基本使用
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<title>百度地图sdk</title>
<script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak= cxetHnP22IpeKLzPLEbmbeCPoeaA0T5L "></script>
<style>
#container{
width: 700px;
height: 500px;
border: 1px solid black;
}
</style>
</head>
<body>
<button>点我加载地图</button>
<div id="container"></div>
<script>
document.querySelector('button').onclick = function (){
var myMap = new BMap.Map("container");
var point = new BMap.Point(116.404, 39.925);
myMap.centerAndZoom(point, 15);
};
</script>
</body>
</html>
控件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<title>百度地图控件</title>
<script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak= cxetHnP22IpeKLzPLEbmbeCPoeaA0T5L "></script>
<style>
#container{
width: 700px;
height: 500px;
border: 1px solid black;
}
</style>
</head>
<body>
<button>点我加载地图</button>
<div id="container"></div>
<script>
document.querySelector('button').onclick = function (){
var myMap = new BMap.Map("container");
var point = new BMap.Point(116.404, 39.925);
myMap.centerAndZoom(point, 15);
// 控件位置设置
/* var options = {
// 控件置于地图左上角
anchor: BMAP_ANCHOR_TOP_LEFT,
// 控件偏移
offset:new BMap.Size(70, 15)
};*/
// 1.系统提供控件
// 平移缩放
/* myMap.addControl(new BMap.NavigationControl());
// 比例尺
myMap.addControl(new BMap.ScaleControl(options));
// 缩略图(右下角箭头)
myMap.addControl(new BMap.OverviewMapControl());
// 卫星地图 三维地图
myMap.addControl(new BMap.MapTypeControl());*/
//2.自定义摆放的系统控件
/*
自定义摆放位置有三个字段可选
anchor:控件摆放位置
offset:控件细节偏移位置
type:控件加载类型
*/
/* var options = {
// 控件位置-右下角
anchor:BMAP_ANCHOR_BOTTOM_RIGHT,
// 偏移位置
offset:new BMap.Size(150, 5),
// 精简类型
type:BMAP_NAVIGATION_CONTROL_SMALL
}
// 添加控件
myMap.addControl(new BMap.NavigationControl(options));*/
//3.自定义控件
// 定义一个控件类,即function
function Fangda(){
// 设置默认停靠位置和偏移量
this.defaultAnchor = BMAP_ANCHOR_TOP_LEFT;
this.defaultOffset = new BMap.Size(10, 10);
}
// 通过JavaScript的prototype属性继承于BMap.Control
Fangda.prototype = new BMap.Control();
// 自定义控件必须实现initialize方法,并且将控件的DOM元素返回
// 在本方法中创建个div元素作为控件的容器,并将其添加到地图容器中
Fangda.prototype.initialize = function(map){
// 创建一个DOM元素
var div = document.createElement("div");
// 添加文字说明
div.appendChild(document.createTextNode("放大2级"));
// 设置样式
div.style.cursor = "pointer";
div.style.border = "1px solid gray";
div.style.backgroundColor = "white";
// 绑定事件,点击一次放大两级
div.onclick = function(e){
myMap.zoomTo(myMap.getZoom() + 2);
}
// 添加DOM元素到地图中
myMap.getContainer().appendChild(div);
// 将DOM元素返回
return div;
}
// 添加到地图当中
myMap.addControl(new Fangda());
};
</script>
</body>
</html>
地址编码与逆编码
地址解析: 地址转换为经纬度
逆解析: 经纬度转为换地址
网友评论