将任意图像转成 HTML5 Canvas

openkk 12年前

在开始讲解技术细节之前请先看这个DEMO,输入任意的图像URL,然后点击 Img2Canvas 按钮

BTW: 同样接受 data-uri 格式数据。

代码:

function draw() {          // Get the canvas element and set the dimensions.           var canvas = document.getElementById('canvas');          canvas.height = window.innerHeight;          canvas.width = window.innerWidth;            // Get a 2D context.          var ctx = canvas.getContext('2d');             // create new image object to use as pattern          var img = new Image();          img.src = document.getElementById('url').value;          img.onload = function(){              // Create pattern and don't repeat!              var ptrn = ctx.createPattern(img,'no-repeat');             ctx.fillStyle = ptrn;             ctx.fillRect(0,0,canvas.width,canvas.height);             }   }

应用逻辑:

关键的地方在于 createPattern()

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

var img = new Image,     canvas = document.createElement("canvas"),     ctx = canvas.getContext("2d"),     src = "http://example.com/image"; // insert image url here      img.crossOrigin = "Anonymous";       img.onload = function() {       canvas.width = img.width;       canvas.height = img.height;       ctx.drawImage( img, 0, 0 );      localStorage.setItem( "savedImageData", canvas.toDataURL("image/png") );    }      img.src = src;    // make sure the load event fires for cached images too    if ( img.complete || img.complete === undefined ) {       img.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";       img.src = src;   }

原文