將任意圖像轉成 HTML5 Canvas

在開始講解技術細節以前請先看這個演示程序,輸入任意的圖像URL,而後點擊 Img2Canvas 按鈕javascript

BTW: 一樣接受 data-uri 格式數據。
html

代碼:html5

01 function draw() {
02         // Get the canvas element and set the dimensions.
03         var canvas = document.getElementById('canvas');
04         canvas.height = window.innerHeight;
05         canvas.width = window.innerWidth;
06   
07        // Get a 2D context.
08         var ctx = canvas.getContext('2d');
09   
10         // create new image object to use as pattern
11         var img = new Image();
12         img.src = document.getElementById('url').value;
13         img.onload = function(){
14             // Create pattern and don't repeat!
15            var ptrn = ctx.createPattern(img,'no-repeat');
16            ctx.fillStyle = ptrn;
17            ctx.fillRect(0,0,canvas.width,canvas.height);
18   
19         }
20  }

應用邏輯:java

關鍵的地方在於 createPattern()canvas

nsIDOMCanvasPattern createPattern(in nsIDOMHTMLElement image, in DOMString repetition);
context.createPattern(image,"repeat|repeat-x|repeat-y|no-repeat");app

01 var img = new Image,
02    canvas = document.createElement("canvas"),
03    ctx = canvas.getContext("2d"),
04    src = "http://example.com/image"; // insert image url here
05  
06   img.crossOrigin = "Anonymous";
07  
08    img.onload = function() {
09      canvas.width = img.width;
10      canvas.height = img.height;
11      ctx.drawImage( img, 0, 0 );
12     localStorage.setItem( "savedImageData", canvas.toDataURL("image/png") );
13   }
14  
15   img.src = src;
16   // make sure the load event fires for cached images too
17   if ( img.complete || img.complete === undefined ) {
18      img.src ="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
19      img.src = src;
20  }

英文原文OSCHINA原創翻譯url

相關文章
相關標籤/搜索