在開始講解技術細節以前請先看這個演示程序,輸入任意的圖像URL,而後點擊 Img2Canvas 按鈕javascript
BTW: 一樣接受 data-uri 格式數據。
html
代碼:html5
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; |
08 |
var ctx = canvas.getContext( '2d' ); |
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' ); |
17 |
ctx.fillRect(0,0,canvas.width,canvas.height); |
應用邏輯:java
關鍵的地方在於 createPattern()canvas
nsIDOMCanvasPattern createPattern(in nsIDOMHTMLElement image, in DOMString repetition);
context.createPattern(image,"repeat|repeat-x|repeat-y|no-repeat");app
02 |
canvas = document.createElement( "canvas" ), |
03 |
ctx = canvas.getContext( "2d" ), |
04 |
src = "http://example.com/image" ; // insert image url here |
06 |
img.crossOrigin = "Anonymous" ; |
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" ) ); |
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==" ; |
英文原文,OSCHINA原創翻譯url