canvas 图片根据滚动条上下移动

canvas滚动条 图片随滚动条移动

<!DOCTYPE html>

<html lang="zh">

<head>

<meta charset="UTF-8">

<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">

<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">

<title></title>

<link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<link href="https://cdn.bootcss.com/font-awesome/4.7.0/css/font-awesome.css" rel="stylesheet">

</head>

<body>

<div class="body">

<div class="col-md-12">

<div class="container">

<div class="row" id="canvas-parent" style="position: relative;">

<canvas id="person" class="person col-md-12 col-xs-12"></canvas>

</div>

</div>

</div>

<footer class="col-md-12">

<div class="container">

<div class="row">

<p class="white text-center">copyright</p>

</div>

</div>

</footer>

</div>

<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
var width = document.getElementById('canvas-parent').offsetWidth;
var height = document.getElementById('canvas-parent').offsetHeight;
var myheight = $(".harm-03").offset().top;
var myCanvas = document.getElementById('person');
var context = myCanvas.getContext('2d');
var image = new Image();
var picSizeX = 66;
var picSizeY = 180;
var getWindowWidth = $(window).width();
var imgY = 0;
var imgX = (width/2-picSizeX/2);
window.onload = function (){
myCanvas.width=width;
myCanvas.height=height;
image.src = 'images/boy.png';
image.onload = function () {
drawImageByLocation(imgX,imgY);
$(window).scroll(function(event){
var wScrollY = window.scrollY;
if(wScrollY - myheight > 0 && wScrollY < (myheight+height-40)){
drawImageByLocation(imgX,wScrollY-myheight);
}
});
}
function drawImageByLocation(x,y) {
context.clearRect(0,0,myCanvas.width,myCanvas.height);
context.drawImage(image,0,0,66,180,x,y,picSizeX,picSizeY);
}
}

</script>

</body>

</html>

  

现看现写的一个小demo,用position:fixed一样可以实现,判断一下滚动条的高度即可。



评论