将任意图像转成 HTML5 Canvas

在开始讲解技术细节之前请先看这个演示程序,输入任意的图像URL,然后点击 Img2Canvas 按钮
BTW: 同样接受 data-uri 格式数据。

代码:

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  }

 

应用逻辑:
关键的地方在于 createPattern()
nsIDOMCanvasPattern createPattern(in nsIDOMHTMLElement image, in DOMString repetition);
context.createPattern(image,"repeat|repeat-x|repeat-y|no-repeat");

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  }

 

英文原文http://www.h3manth.com/content/convert-any-image-html5-canvas,OSCHINA原创翻译

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

Grow your business fast with

Suku