我有一个动态创建的canvas元素,它覆盖了所有其他元素。调整大小时,画布完美贴合屏幕,没有任何问题。 我认为相同的原理适用于滚动,但它没有:
var a = document.createElement('canvas');
createCanvas();
function createCanvas(){
a.height = $(window).height();
a.width = $(window).width();
a.id = "some_canvas";
a.style.opacity = "0.8";
a.style.position = "absolute";
document.body.insertBefore(a,document.body.firstChild);
context = a.getContext("2d");
context.fillStyle = "#000000";
context.fillRect(0, 0, a.width, a.height);
}
$(window).resize(function(){
$("some_canvas").remove();
createCanvas();
});
$(window).scroll(function(){
$("#some_canvas").remove();
createCanvas();
});
https://jsfiddle.net/9mfxytoz/1/
画布仍保留其最后的尺寸调整,但不会滚动。我试图制作它,以便即使在滚动时也可以看到画布。
答案 0 :(得分:0)
试试这个:
<canvas id="Canvas2D"></canvas>
CSS:
html, body {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
#Canvas2D {
position:absolute;
top:0;
left:0;
}
这里有JS要求它全部工作:
// set the width and height to the full windows size
var SCREEN_WIDTH = window.innerWidth;
// Change to scroll height to make it the size of the document
var SCREEN_HEIGHT = document.documentElement.scrollHeight;
// Make sure to set the canvas to the screen height and width.
canvas.width = SCREEN_WIDTH;
canvas.height = SCREEN_HEIGHT;
// everytime we resize change the height and width to the window size, and reset the
// center point
window.onresize = function () {
SCREEN_HEIGHT = canvas.height = document.documentElement.scrollHeight;
SCREEN_WIDTH = canvas.width = document.body.offsetWidth;
HALF_WIDTH = SCREEN_WIDTH / 2;
HALF_HEIGHT = SCREEN_HEIGHT / 2;
};