canvas中图片、视频的加载(截图、切片)
1.图片的加载 必须用load事件加载,确保图片加载完成了,才能进行添加到canvas中
-
drawImage(image, x, y) 添加图片和图片的放置的位置
-
drawImage(image, x, y, width, height) 添加图片放置,并缩放大小
-
drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight) 前4个是定义图像源的切片位置和大小,后4个则是定义切片的目标显示位置和大小。
-
常用场景1)精灵图的使用
var img=new Image();
img.addEventListener("load",loadHandler);
img.src="./img/new_icon.png";
function loadHandler(e){
// 参数分别为:图源,精灵图X偏移,Y偏移,内容宽度,高度,放在canvas上的坐标X,y,宽,高
ctx.drawImage(img,128,126,14,14,100,100,14,14);//精灵图绘制
}
*常用场景2)放大镜
js代码
<script>
var canvas=document.querySelector("canvas");
var div0=document.querySelector(".div0");
var div1=document.querySelector(".div1");
var ctx=canvas.getContext("2d");
var img=document.querySelector("img");
var rect;
var x=0;
var y=0;
init();
function init(){
rect=div0.getBoundingClientRect();
if(!img.width){
img.addEventListener("load",loadHandler);
}else{
div0.addEventListener("mouseenter",mouseHandler);
}
}
function loadHandler(e){
img.removeEventListener("load",loadHandler);
div0.addEventListener("mouseenter",mouseHandler);
}
function mouseHandler(e){
if(e.type==="mouseenter"){
canvas.style.display="block";
div0.addEventListener("mousemove",mouseHandler);
div0.addEventListener("mouseleave",mouseHandler);
}else if(e.type==="mousemove"){
x=e.clientX-rect.x-50;
y=e.clientY-rect.y-40;
if(x<0) x=0;
if(x>rect.width-100) x=rect.width-100;
if(y<0) y=0;
if(y>rect.height-80) y=rect.height-80;
div1.style.left=x+"px";
div1.style.top=y+"px";
drawImgs(x,y,100,80);
}else if(e.type==="mouseleave"){
// canvas.style.display="none";
div0.removeEventListener("mousemove",mouseHandler);
div0.removeEventListener("mouseleave",mouseHandler);
}
}
function drawImgs(x,y,width,height){
ctx.clearRect(0,0,500,407);
ctx.drawImage(img,x,y,width,height,0,0,500,407);
}
</script>
html
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.div0{
500px;
height: 407px;
position: relative;
float: left;
}
.div1{
100px;
height:80px;
background-color:rgba(255,0,0,0.2);
position: absolute;
left:0px;
top:0px;
}
canvas{
display: none;
}
</style>
</head>
<body>
<div class="div0">
<img src="./img/16.jpg">
<div class="div1"></div>
</div>
<canvas width="500" height="407"></canvas>
</body>
</html>
2.视频截图
js代码
var canvas=document.querySelector("canvas");
var ctx=canvas.getContext("2d");
var mp4=document.querySelector("video");
var bn=document.querySelector("button");
bn.addEventListener("click",clickHandler);
function clickHandler(e){
ctx.drawImage(mp4,0,0,536,480);
}
html
<video src="./video/test3.mp4" controls autoplay></video> //视频自己引入
<button>截图</button>
<canvas width="536" height="480"></canvas>