知道<canvas>嗎?若是你不熟悉<canvas>,學習他的最好方法是去看一個簡單的例子。下面的HTML和JavaScript將在<canvas>域內生成一個橙色的矩形區域。推薦學習相關HTML高級教程。web
<canvas id="example1" width="400" height="300"></canvas>
// get the canvasvar canvas = document.getElementById('example1');//
get the "2d" contextvar context = canvas.getContext('2d');//
change fill style to orangecontext.fillStyle = '#ff7700';//
draw an orange rectanglecontext.fillRect(0, 0, 400, 300);
你老是經過找到web文檔中的元素,而後選擇「context」開始canvas繪畫。在本例中, context是2 d, 由於咱們想用canvas 畫二維形狀。選擇一個context以後,canvas API包含了不少有用的繪圖功能,如填充樣式,形狀,中風,陰影,和大量的其餘特性,容許咱們給 圖片作出奇特的改變。咱們的編寫的腳本的結果看起來是 這樣的 。
<canvas>的偉大之處就是它是一個JavaScript API,這意味着咱們能夠利用全部的JavaScript變量,事件,循環 等等的特色。讓咱們應用咱們的腳本使用一個簡單的JavaScript循環在咱們的canvas區域建立一個網格的小區域。
<canvas id="example2" width="400" height="300"></canvas>
// get the canvas and contextvar canvas = document.getElementById('example2');
var context = canvas.getContext('2d');// orange fill stylecontext.fillStyle = '#ff7700';//
create squares in a loopfor(var x = 0; x < canvas.width; x += 25){ for(var y = 0; y
< canvas.height; y += 25){ context.fillRect(x, y, 20, 20); }}
短短几行JavaScript, 在咱們的canvas區域可以產生192個方塊。在我看來,這是<canvas>的真正價值。它容許咱們利用web瀏覽器的處理能力來生成數學幾何和圖紙。再加上一點工做和大量的創造力,咱們甚至能夠利用這種力量的實現 藝術效果。
動畫canvas
在咱們繼續這個話題以前,咱們須要瞭解如何使用<canvas>建立一個動畫。這是一個有點更難作的事情。首先,請理解,以阻礙web瀏覽器 性能的方式使用canvas API是很容易的。在canvas上繪畫是須要處理器密集型的工做,特別是若是你不斷更新動畫之類的圖紙。緩解任何性能問 題,我將使用一個新功能叫作requestAnimationFrame,容許咱們的web瀏覽器來決定更新canvas的頻率, 同時在咱們的web文 檔保持最佳性能。這不是在全部瀏覽器均可用的, 但幸運的是保羅愛爾蘭曾寫過一個出色的poly-fill將此功能添加到舊版本的web瀏覽器。他在他的博客寫下了這個腳本和web瀏覽器這個的特性。瀏覽器
爲了簡便起見,我不打算在個人代碼示例中包含保羅的腳本,可是你應該在本身的代碼中使用它。使用requestAnimationFrame,咱們能夠在咱們的腳本中建立一個基本的「動畫循環」。它看上去是 這樣的
<canvas id="example3" width="400" height="300"></canvas>
// get the canvasvar canvas = document.getElementById('example3');var context =
canvas.getContext('2d');context.fillStyle = '#ff7700';var time = false;//
box positionvar x = -100;// animation loopvar loop = function(){ //
get time since last frame var now = new Date().getTime();
var d = now - (time || now); time = now; // clear previously
drawn rectangles context.clearRect(0, 0, canvas.width, canvas.height);
// draw new rectangle context.fillRect(x, 100, 100, 100);
// advance horizontal position x += 0.1 * d;
// reset horizontal position if(x > canvas.width){ x = -100; } //
request next frame requestAnimationFrame(loop);};// first frameloop();
當在canvas元素中使用動畫, 全部繪畫應由一個可重複的函數完成。在示例中,使用loop()函數在咱們的canvas上畫一個正方形。 requestAnimationFrame函數基於可用的處理能力告訴瀏覽器時自動選擇何時繪製下一個框架,結果是咱們的loop()函數一遍又一 遍的運行, 從左到右推動咱們的橙色盒子前進。請注意,咱們使用d變量(delta)來肯定幀之間的時間,以毫秒爲單位。這是使咱們的動畫速度正常的一個 重要的增長項。沒有它,咱們的動畫在有好一點的處理器的計算機上會跑的更快,幾年後當電腦得到更多的處理能力,咱們的動畫能夠跑的更快之快,以致於混淆或 誤導用戶。使用delta變量,咱們能夠每毫秒指定一個速度。在咱們的示例中, 方塊的位置每毫秒前進0.1 * d,或0.1像素,轉化後即爲每秒 100像素。不管您的處理器的速度是多少, 動畫老是花一樣多的時間完成。
藝術元素
既然咱們瞭解canvas元素以及如何使用它建立動畫,咱們能夠在這些基礎上加上一些藝術創造力來創造更有意思的東西。在下一個示例中,咱們將在canvas元素中隨機生成彩色圓圈而且和給他們隨機軌跡。經過使用漸變畫圓圈而不是純色,咱們的「北極光」腳本變得生動起來。
<canvas id="example4" width="400" height="300" style="#0e74a2;"></canvas>
// get the canvasvar canvas = document.getElementById('example4');var context =
canvas.getContext('2d');var time = false;// create an empty array of "circles"var circles
= [];// animation loopvar loop = function(){ // get time since last frame var now = new Date().getTime();
var d = now - (time || now); time = now; // clear the canvas context.clearRect(0, 0, canvas.width,
canvas.height); // draw circles for(var i = 0; i < circles.length; i++){
circles[i].update(d); circles[i].draw(); } // request next frame requestAnimationFrame(loop);};//
circle objectvar circle = function(options){ // configuration var circle = this; circle.settings =
{ x: 0, y: 0, radius: 20, orientation: 0,
vector: { x: 0, y: 0 }, speed: 1, color: { red: 0, green: 0, blue: 0, alpha: 1 } };
// merge options into settings var newsettings = {};
for(var attrname in circle.settings){ newsettings[attrname]
= circle.settings[attrname]; } for(var attrname in options){ newsettings[attrname] = options[attrname]; }
circle.settings = newsettings; // update circle circle.update = function(d){ // update position
circle.settings.x += circle.settings.vector.x * circle.settings.speed * d;
circle.settings.y += circle.settings.vector.y * circle.settings.speed * d; // bounce
if(circle.settings.x < 0 && circle.settings.vector.x < 0 || circle.settings.x >
canvas.width && circle.settings.vector.x > 0){ 框架
circle.settings.vector.x = circle.settings.vector.x * -1; } dom
if(circle.settings.y < 0 && circle.settings.vector.y < 0 || circle.settings.y >
canvas.height && circle.settings.vector.y > 0){
circle.settings.vector.y = circle.settings.vector.y * -1;
} }; // draw circle circle.draw = function(){ // gradient fill var gradient =
context.createRadialGradient(circle.settings.x, circle.settings.y,
circle.settings.radius / 10, circle.settings.x, circle.settings.y, circle.settings.radius);
gradient.addColorStop(0, 'rgba(' + circle.settings.color.red + ', ' + circle.settings.color.green
+ ', ' + circle.settings.color.blue + ', ' + circle.settings.color.alpha + ')');
gradient.addColorStop(1, 'rgba(' + circle.settings.color.red + ', ' + circle.settings.color.green
+ ', ' + circle.settings.color.blue + ', ' + circle.settings.color.alpha / 50 + ')');
context.fillStyle = gradient; // draw context.beginPath();
context.arc(circle.settings.x, circle.settings.y, circle.settings.radius, 0, 2 * Math.PI, false);
context.fill(); };};// create new circlesvar newcircles = function(){ // remove old circles circles
= []; // create 5 new circles for(var i = 0; i < 5; i++){ // create a new circle
var newcircle = new circle({ x: Math.floor(Math.random() * canvas.width),
y: Math.floor(Math.random() * canvas.height),
radius: Math.floor(Math.random() * canvas.width),
orientation: Math.floor(Math.random() * 360),
vector: { x: Math.random() / 40,
y: Math.random() / 40 }, speed: Math.random(),
color: {
red: 100 + Math.floor(Math.random() * 155),
green: 100 + Math.floor(Math.random() * 155),
blue: 100 + Math.floor(Math.random() * 155),
alpha: 0.1 + Math.random() } });
// add new circle to circles array
circles.push(newcircle);
}};// generate new circleswindow.addEventListener('click', newcircles, false);
window.addEventListeneride
('touchend', newcircles, false);newcircles();// first frameloop();函數
在這個窗口每次單擊,新的隨機圓圈將會出現。
咱們纔剛剛開始理解和利用<canvas>的力量。我渴望瞭解這個行業如何採用它以及SVG等技術構建驚奇和藝術的web內容。在個人下一篇 文章中,我將展現如何採用此代碼使用鍵盤快捷鍵和動畫來建立一個簡單的基於canvas的遊戲,讓你能夠在web瀏覽器中玩這種遊戲。還有更多HTML教程視頻供你學習沒請登陸e良師益友網。oop