創造運用淺談canvas的設計藝術

來源:互聯網
上載者:User

標籤:style   http   io   color   ar   os   使用   java   for   

知道<canvas>嗎?如果你不熟悉<canvas>,學習他的最好方法是去看一個簡單的例子。下面的HTML和JavaScript將在<canvas>域內產生一個橙色的矩形地區。推薦學習相關HTML進階教程。

<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 畫2D 圖形。選擇一個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>建立一個動畫。這是一個有點更難做的事情。首先,請理解,以阻礙web瀏覽器 效能的方式使用canvas API是很容易的。在canvas上繪畫是需要處理器密集型的工作,特別是如果你不斷更新動畫之類的圖紙。緩解任何效能問 題,我將使用一個新功能叫做requestAnimationFrame,允許我們的web瀏覽器來決定更新canvas的頻率, 同時在我們的web文 檔保持最佳效能。這不是在所有瀏覽器都可用的, 但幸運的是保羅愛爾蘭曾寫過一個出色的poly-fill將此功能添加到舊版本的web瀏覽器。他在他的部落格寫下了這個指令碼和web瀏覽器這個的特性。

為了簡便起見,我不打算在My Code樣本中包含保羅的指令碼,但是你應該在自己的代碼中使用它。使用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;    }  

 

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.addEventListener

(‘touchend‘, newcircles, false);newcircles();// first frameloop();

在這個視窗每次單擊,新的隨機圓圈將會出現。
我們才剛剛開始理解和利用<canvas>的力量。我渴望瞭解這個行業如何採用它以及SVG等技術構建驚奇和藝術的web內容。在我的下一篇 文章中,我將展示如何採用此代碼使用鍵盤快速鍵和動畫來建立一個簡單的基於canvas的遊戲,讓你可以在web瀏覽器中玩這種遊戲。還有更多HTML教程視頻供你學習沒請登入e良師益友網。

 

創造運用淺談canvas的設計藝術

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.