canvas图片操作
图片动画,一条游动的鱼
//核心代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style media="screen">
body {background:black; text-align:center;}
#c1 {background:white;}
</style>
<script>
window.onload=function (){
let oC=document.getElementById('c1');
let gd=oC.getContext('2d');
let pause=false;//控制是否暂停游动,默认是否
let i=0;//图片下标
let x=100;//默认起始位置
let frameCounter=0;//动画计数器
let oImg=new Image();
oImg.src='fish1.png';//一张游动的鱼,行走图
oImg.onload=function (){
requestAnimationFrame(next);//调用帧动画
function next(){
if(!pause){//如果没有暂停
gd.clearRect(0, 0, oC.width, oC.height);//清除原图片
if(frameCounter%4==0){//动画计数器,用来控制动画频率
i++;//切换图片
if(i==4)i=0;//超过第四张图片就回到第一张
}
x+=1.5;//鱼的位置+1.5,向前进
//画鱼,连续切换行走图,实现原地游动,x++实现向前游动
gd.drawImage(
oImg,
//sx, sy, sw, sh
0, i*37, 55, 37,
//dx, dy, dw, dh
x, 100, 55, 37
);
frameCounter++;//计数器++
}
requestAnimationFrame(next);//递归调用帧动画
}
};
document.onclick=function (){
pause=!pause;//控制点击暂停
};
};
</script>
</head>
<body>
<canvas id="c1" width="800" height="600"></canvas>
</body>
</html>
canvas像素级操作
window.onload=function (){
let oC=document.getElementById('c1');
let gd=oC.getContext('2d');
let W=oC.width,H=oC.height;
let oImg=new Image();
oImg.src='http://localhost/2018-3-20/2.jpg';
oImg.onload=function (){
gd.drawImage(oImg, 0, 0);
let imageData=gd.getImageData(0, 0, W, H);
let data=imageData.data;
for(let r=0;r<H;r++){
for(let c=0;c<W;c++){
//(r*W+c)*4 行*宽+列可以得到像素点,*4得到RGBA
//(r*W+c)*4+0 => r
//(r*W+c)*4+1 => g
//(r*W+c)*4+2 => b
//(r*W+c)*4+3 => a
data[(r*W+c)*4+0]=data[(r*W+c)*4+1]=data[(r*W+c)*4+2]=
1.0*(data[(r*W+c)*4+0]+data[(r*W+c)*4+1]+data[(r*W+c)*4+2])/3;//除以3得到平均值,就是灰色,乘以倍数即可提高亮度
}
}
gd.putImageData(imageData, 0, 0);
};
};
canvas视频(video)操作
<script>
window.onload=function (){
let oV=document.getElementById('v1');
let oC=document.getElementById('c1');
let gd=oC.getContext('2d');
let W=oC.width,H=oC.height;
requestAnimationFrame(next);
function next(){
gd.drawImage(oV, 0, 0);
//
let imageData=gd.getImageData(0, 0, W, H);
let data=imageData.data;
for(let r=0;r<H;r++){
for(let c=0;c<W;c++){
data[(r*W+c)*4+0]=data[(r*W+c)*4+1]=data[(r*W+c)*4+2]=
(data[(r*W+c)*4+0]+data[(r*W+c)*4+1]+data[(r*W+c)*4+2])/3;
}
}
gd.putImageData(imageData, 0, 0);
requestAnimationFrame(next);
}
};
</script>
</head>
<body>
<video src="movie.ogg" id="v1" autoplay loop style="display:none;"></video>
<canvas id="c1" width="320" height="240"></canvas>
</body>
网友评论