Canvas实现截图效果
html使用video播放视频,canvas面板截图以及一个备份的canvas面板.
<video id="video" autoplay="true" width="500" height="400">
<source src="http://vjs.zencdn.net/v/oceans.mp4" type="video/mp4"></source>
<source src="http://vjs.zencdn.net/v/oceans.webm" type="video/webm"></source>
<source src="http://vjs.zencdn.net/v/oceans.ogv" type="video/ogg"></source>
</video>
<canvas id="temp" width="500" height="400" style="display:none"></canvas>
<canvas id="canvas" width="500" height="400" ></canvas>
<button id="btn">截取</button>
下面是相关js实现,至于其他的重绘,清空面板等代码没有贴出来.
var canvas = $("#canvas"),
ctx = canvas[0].getContext("2d"),
position = {},
canvasRect = {},
line = [],//记录绘制的线
check = false,//记录是否按住鼠标左键
width = $("#video").width(),
height = $("#video").height();
//截图
function drawImg(){
$("#temp")[0].getContext("2d").drawImage($("#video")[0], 0, 0, width, height);//设置一个备份图像
ctx.drawImage($("#temp")[0], 0, 0, width, height);
}
//事件
(function event(){
//截图
$("#btn").on("click", function(){
drawImg();
});
//鼠标左键按下
canvas.on("mousedown", function(e){
canvasRect = canvas[0].getBoundingClientRect(),
position.x1 = e.clientX - canvasRect.left;
position.y1 = e.clientY - canvasRect.top;
});
//移动
$("#canvas").on("mousemove", function(e){//移动的时候画线
if(!check) return;
ctx.lineWidth = 2;
ctx.clearRect(0, 0, width, height);
ctx.drawImage($("#temp")[0], 0, 0, width, height); //从备份中取图像
ctx.strokeStyle = 'red';
drawLine(line);//绘制已经存在的线
position.x2 = Math.round(e.clientX - canvasRect.left);
position.y2 = Math.round(e.clientY - canvasRect.top);
ctx.beginPath();
ctx.moveTo(position.x1, position.y1);
ctx.lineTo(position.x2, position.y2);
ctx.stroke();
drawLinePloy(position.x1, position.y1, position.x2, position.y2, ctx);//绘制箭头
});
//鼠标松开
canvas.on("mouseup", function(e){
check = false;
ctx.clearRect(0, 0, canvas.width(), canvas.height());
ctx.drawImage($("#temp")[0], 0, 0, width, height); //从备份中取图像
position.x2 = e.clientX - canvasRect.left;
position.y2 = e.clientY - canvasRect.top;
ctx.strokeStyle ='red';
drawLine(line);//绘制已经存在的线
ctx.beginPath();
ctx.moveTo(position.x1, position.y1);
ctx.lineTo(position.x2, position.y2);
line.push(JSON.parse(JSON.stringify(position)));
drawLinePloy(position.x1, position.y1, position.x2, position.y2, ctx);//绘制箭头
ctx.stroke();
});
function drawLine(){
//绘制已经存在的线
line.forEach(function(item){
ctx.beginPath();
ctx.moveTo(item.x1, item.y1);
ctx.lineTo(item.x2, item.y2);
ctx.stroke();
drawLinePloy(item.x1, item.y1, item.x2, item.y2, ctx);//画箭头
});
}
//绘制箭头
function drawLinePloy(x1, y1, x2, y2, ctx){
var angle = Math.abs(Math.atan((x2 - x1) / (y2 - y1))),//倾斜角余角
length = 10, //箭头斜线长度
degree = Math.PI / 6, //箭头倾斜角
theta = 0,
altha = 0,
a1 = 0,
b1 = 0,
a2 = 0,