Canvas填滿瀏覽器視窗操作(九)
阿新 • • 發佈:2018-12-12
首先如何畫一個鋪滿瀏覽器的canvas,有人會想這樣
context.fillRect(0,0,100%,100%);然而很不幸,這是無效的!
那怎麼來呢??使用以下函式,在加上上一篇已經說了canvas.attr可以重置Canvas的高和寬,
$(window).get(0).innerWidth
$(window).get(0).innerHeight
這2個是返回瀏覽器的寬和高
所以有程式碼如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>html5</title> <script type="text/javascript" src="jquery-3.1.1.min.js"></script> <script type="text/javascript" >$(document).ready(function(){ var canvas = $("#myCanvas"); var context = canvas.get(0).getContext("2d"); canvas.attr("width",$(window).get(0).innerWidth); canvas.attr("height",$(window).get(0).innerHeight); context.fillStyle = "#12ad31"; context.fillRect(0,0,canvas.width(),canvas.height()); })</script> </head> <body> <canvas id="myCanvas"> <!-- no no no no --> </canvas> </body> </html>
效果圖:
我們發現其實還是有一點距離的,看左上角!!!
這個時候我們需要加點css來填滿!!!
建立一個css檔案並引用!!!
css程式碼如下
*{margin: 0;padding: 0;}
html,body{height: 100%;width: 100%;}
canvas{display: block;}
html5程式碼:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>html5</title> <link href="html5.css" rel="stylesheet" type="text/css"> <script type="text/javascript" src="jquery-3.1.1.min.js"></script> <script type="text/javascript" >$(document).ready(function(){ var canvas = $("#myCanvas"); var context = canvas.get(0).getContext("2d"); canvas.attr("width",$(window).get(0).innerWidth); canvas.attr("height",$(window).get(0).innerHeight); context.fillStyle = "#12ad31"; context.fillRect(0,0,canvas.width(),canvas.height()); })</script> </head> <body> <canvas id="myCanvas"> <!-- no no no no --> </canvas> </body> </html>
效果圖:這樣就ok了!!!
但是當我們改變瀏覽器視窗大小,會出現滾動條,如何去掉適應視窗呢??
有個函式調整視窗大小就會觸發,所以我們只要在這個觸發函式李重置canvas的大小就ok了
觸發函式
$(window).resize(resizeCanvas);
程式碼如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>html5</title> <link href="html5.css" rel="stylesheet" type="text/css"> <script type="text/javascript" src="jquery-3.1.1.min.js"></script> <script type="text/javascript" >$(document).ready(function(){ var canvas = $("#myCanvas"); var context = canvas.get(0).getContext("2d"); canvas.attr("width",$(window).get(0).innerWidth); canvas.attr("height",$(window).get(0).innerHeight); context.fillStyle = "#12ad31"; context.fillRect(0,0,canvas.width(),canvas.height()); //視窗大小改變就呼叫resizeCanvas函式 $(window).resize(resizeCanvas); //重置函式 function resizeCanvas(){ canvas.attr("width",$(window).get(0).innerWidth); canvas.attr("height",$(window).get(0).innerHeight); context.fillStyle = "#12ad31"; context.fillRect(0,0,canvas.width(),canvas.height()); }; })</script> </head> <body> <canvas id="myCanvas"> <!-- no no no no --> </canvas> </body> </html>
這樣就不會出現滾動條了!!!