任意の画像をHTML 5 Canvasに変換

4036 ワード

技術の詳細を説明する前に、このデモプログラムを見て、任意の画像URLを入力し、Img 2 canvasボタンをクリックしてください.
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");
view source
print ? 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オリジナル翻訳