(function($) {
$(window).load(function() {
$("html").niceScroll();
});
})(jQuery);
var timeOut;
window.onresize = function() {
if (timeOut)
clearTimeout(timeOut);
timeOut = setTimeout(draw, 10);
}
window.onload = draw;
window.onscroll = navigate;
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext('2d');
forest = new Image;
forest.src = 'http://p1.pichost.me/i/33/1561150.jpg';
function navigate() {
draw()
}
function draw(scroll) {
scroll = (window.scrollY || window.pageYOffset)/(document.body.clientHeight - window.innerHeight) * 3000;
canvas.setAttribute('width', window.innerWidth);
canvas.setAttribute('height', window.innerHeight);
drawImageProp(ctx, forest, 0, (-scroll * 3.9)/4, canvas.width, canvas.height + (scroll * 3.9)/2);
}
function drawImageProp(ctx, img, x, y, w, h, offsetX, offsetY) {
if (arguments.length === 2) {
x = y = 0;
w = ctx.canvas.width;
h = ctx.canvas.height;
}
// default offset is center
offsetX = typeof offsetX === "number" ? offsetX : 0.5;
offsetY = typeof offsetY === "number" ? offsetY : 0.5;
// keep bounds [0.0, 1.0]
if (offsetX < 0) offsetX = 0;
if (offsetY < 0) offsetY = 0;
if (offsetX > 1) offsetX = 1;
if (offsetY > 1) offsetY = 1;
var iw = img.width,
ih = img.height,
r = Math.min(w/iw, h/ih),
nw = iw * r, // new prop. width
nh = ih * r, // new prop. height
cx, cy, cw, ch, ar = 1;
// decide which gap to fill
if (nw < w) ar = w/nw;
if (nh < h) ar = h/nh;
nw *= ar;
nh *= ar;
// calc source rectangle
cw = iw/(nw/w);
ch = ih/(nh/h);
cx = (iw - cw) * offsetX;
cy = (ih - ch) * offsetY;
// make sure source rectangle is valid
if (cx < 0) cx = 0;
if (cy < 0) cy = 0;
if (cw > iw) cw = iw;
if (ch > ih) ch = ih;
// fill image in dest. rectangle
ctx.drawImage(img, cx, cy, cw, ch, x, y, w, h);
}
body {
height: 1000vh;
margin: 0;
}
canvas {
width: 100%;
height: 100vh;
position: fixed;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="view-source:http://areaaperta.com/nicescroll/js/jquery.nicescroll.min.js"></script>
<canvas id="canvas"></canvas>
这个插件并不用帆布工作。尝试使用'$('body')'选择器。 – mwl
@mwl它也没有工作 –