html5 Canvas 如何自适应屏幕大小
4个回答
推荐于2018-02-26
展开全部
只有内嵌css有效,外部css会出现拉伸的情况,
所以有两种方案
var myCanvas = "<canvas id='myCanvas' width='" + screen.availWidth + "px' height='"+ screen.availHeight + "px'></vanvas>";
document.body.insertAdjacentHTML("beforeEnd", myCanvas);
或者这种做法
var myCanvas = document.createElement("canvas");
myCanvas.setAttribute("width", screen.availWidth);
myCanvas.setAttribute("height", screen.availHeight);
myCanvas.setAttribute("id", "myCanvas");
document.body.appendChild(myCanvas);
两种方案的共性都是在把元素添加进DOM前设置他的大小
估计是没分了,给后人看吧
所以有两种方案
var myCanvas = "<canvas id='myCanvas' width='" + screen.availWidth + "px' height='"+ screen.availHeight + "px'></vanvas>";
document.body.insertAdjacentHTML("beforeEnd", myCanvas);
或者这种做法
var myCanvas = document.createElement("canvas");
myCanvas.setAttribute("width", screen.availWidth);
myCanvas.setAttribute("height", screen.availHeight);
myCanvas.setAttribute("id", "myCanvas");
document.body.appendChild(myCanvas);
两种方案的共性都是在把元素添加进DOM前设置他的大小
估计是没分了,给后人看吧
展开全部
可以用JS监控屏幕大小,然后调整Canvas的大小。在代码中加入JS
$(window).resize(resizeCanvas);
function resizeCanvas() {
canvas.attr("width", $(window).get(0).innerWidth);
canvas.attr("height", $(window).get(0).innerHeight);
context.fillRect(0, 0, canvas.width(), canvas.height());
};
resizeCanvas();
就可以了。
<canvas> 标签只是图形容器,您必须使用脚本来绘制图形。
本回答被网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
<canvas id="canvas" style="background-color: #000022;position:absolute;top:0;left:0;"></canvas>
<script>
var canvas = document.getElementById("canvas");//获取canvas
function resizeCanvas(canvasElement){
canvasElement.width = window.innerWidth;
canvasElement.height = window.innerHeight;
}//这个函数会吧canvas元素的大小变成和浏览器窗口一样大
//添加监听改变窗口大小的事件
window.onresize = function(){
resizeCanvas(canvas);
}
// 需要注意的是改变canvas元素的长宽会清除该canvas
</script>
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
css样式设置width:100%;height:100%;然后用下面四种方法皆可:
1.
canvas.width = document.documentElement.clientWidth;
canvas.height = document.documentElement.clientHeight;
2.
canvas.width = screen.availWidth;
canvas.height = screen.availHeight;
3.
canvas.width = screen.width;
canvas.height = screen.height;
4.
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
1.
canvas.width = document.documentElement.clientWidth;
canvas.height = document.documentElement.clientHeight;
2.
canvas.width = screen.availWidth;
canvas.height = screen.availHeight;
3.
canvas.width = screen.width;
canvas.height = screen.height;
4.
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询