2011年4月14日 星期四

以Canvas globalCompositeOperation屬性製作CropCircle

Jimmy's papa很喜歡麥田圈的美麗又兼具高度對稱性,早就想讓Jimmy試著用Scratch畫畫看,可惜目前Scratch的畫圖功能有點陽春,無法作到兩個圖形的各種合成操作,幸好HTML canvas提供globalCompositeOperation屬性,可以很輕鬆的寫出javascript程式碼畫出簡單的麥田圈,嗯!晚上再一圈一圈的畫給Jimmy看,讓他看看爸爸也可以畫出外星人的麥田圈,呵呵!!!

如果你看的左邊大圖(程式線上畫出來的)與右邊小圖是不一樣的話,你的瀏覽器有可能是IE or Opera
Your browser does not support the canvas element.
畫麥田圈的javascript程式碼如下
var c=document.getElementById("JimmyScratchLab_myCropCircle0413");
var context=c.getContext("2d");
  context.fillStyle   = '#000000';
  context.strokeStyle = '#f00';
  context.lineWidth   = 4;

  context.beginPath();
  context.arc(150, 150, 150, 0, 360, false);
  context.closePath();
  context.fill();

context.globalCompositeOperation = "xor";

  context.beginPath();  
  context.arc(150, 90, 60, 0, 360, false);  
  context.closePath();
  context.fill();

context.globalCompositeOperation = "xor";

  context.beginPath();  
  context.arc(100, 120, 60, 0, 360, false);  
  context.closePath();
  context.fill();

context.globalCompositeOperation = "xor";

  context.beginPath();  
  context.arc(100, 180, 60, 0, 360, false);  
  context.closePath();
  context.fill();

context.globalCompositeOperation = "xor";

  context.beginPath();  
  context.arc(150, 210, 60, 0, 360, false);  
  context.closePath();
  context.fill();

context.globalCompositeOperation = "xor";

  context.beginPath();  
  context.arc(205, 180, 60, 0, 360, false);  
  context.closePath();
  context.fill();

context.globalCompositeOperation = "xor";

  context.beginPath();  
  context.arc(205, 120, 60, 0, 360, false);  
  context.closePath();
  context.fill();
//-----------------
context.globalCompositeOperation = "xor";

  context.beginPath();  
  context.arc(100, 60, 30, 0, 360, false);  
  context.closePath();
  context.fill();

context.globalCompositeOperation = "xor";

  context.beginPath();  
  context.arc(50, 150, 30, 0, 360, false);  
  context.closePath();
  context.fill();

context.globalCompositeOperation = "xor";

  context.beginPath();  
  context.arc(100, 240, 30, 0, 360, false);  
  context.closePath();
  context.fill();

context.globalCompositeOperation = "xor";

  context.beginPath();  
  context.arc(200, 240, 30, 0, 360, false);  
  context.closePath();
  context.fill();

context.globalCompositeOperation = "xor";

  context.beginPath();  
  context.arc(250, 150, 30, 0, 360, false);  
  context.closePath();
  context.fill();

context.globalCompositeOperation = "xor";

  context.beginPath();  
  context.arc(200, 60, 30, 0, 360, false);  
  context.closePath();
  context.fill();
//--------------------------
context.globalCompositeOperation = "destination-out";

  context.beginPath();  
  context.arc(150, 150, 60, 0, 360, false);  
  context.closePath();
  context.fill();

//--------------------------
context.globalCompositeOperation = "copy";

  context.beginPath();  
  context.arc(150, 150, 20, 0, 360, false);  
  context.closePath();
  context.fill();

沒有留言:

張貼留言