2014-02-21 296 views

回答

2

您可以使用drawImage()方法的裁剪參數並將裁剪後的圖像繪製到動態創建的畫布上。

一個例子可以是:

function getClippedRegion(image, x, y, width, height) { 

    var canvas = document.createElement('canvas'), 
     ctx = canvas.getContext('2d'); 

    canvas.width = width; 
    canvas.height = height; 

    //     source region   dest. region 
    ctx.drawImage(image, x, y, width, height, 0, 0, width, height); 

    return canvas; 
} 

這將返回一個canvas元素與已經繪製的截取圖像。您現在可以直接使用畫布將其繪製到另一個畫布上。

使用示例;在你的主代碼,你可以這樣做:

var canvas = document.getElementById('myScreenCanvas'), 
    ctx = canvas.getContext('2d'), 
    image = document.getElementById('myImageId'), 
    clip = getClippedRegion(image, 50, 20, 100, 100); 

// draw the clipped image onto the on-screen canvas 
ctx.drawImage(clip, canvas.width * Math.random(), canvas.height * Math.random()); 
2

....或者你可以只使用CSS精靈技術,它是更快,更容易。

如果您有圖像(例如my_Image.gif),並且您打算僅使用此方法提取一部分圖像,則可以將提取圖像模擬爲DIV元素的背景。請參閱下面的代碼。下面簡單的說

portion1 ID參數「從我的形象,片100px的高度和位置0像素左側(保證金左)和0像素的頂部(邊距)100像素寬」

部分2下面的ID參數簡單地說:「從我的圖像,切片100px高和100px寬從位置-91px到左(margin-left)和0px到top(margin-top)」

用這個,你可以通過簡單地操作像素就可以從任何位置切割任何尺寸。你也可以使用%。

注:您的圖片必須是gif格式在這種情況下,必須駐留在您的服務器的根......

您可以使用其他附加圖片... JPEG,PNG等

<!DOCTYPE html> 
     <html> 
     <head> 
      <style> 

      #portion1 { 
       width: 100px; 
       height: 100px; 
       background: url(my_Image.gif) 0 0; 
      } 

      #portion2 { 
       width: 100px; 
       height: 100px; 
       background: url(my_Image.gif) -91px 0; 
      } 
      </style> 
      </head> 
      <body> 


      <div id="portion1"></div><br> 
      <div id="portion2"></div> 


       <script> 
       //creating the array to hold the portions 
       var ImagePortions = [ 
       "url('my_Image.gif') 0 0 ", 
       "url('my_Image.gif') -91px 0"]; 

/*You can now create your canvas container that will act as the parent of these array elements and use Math.random() to display the portions*/ 


     </script> 


     </body> 
     </html> 
+0

不錯的主意,簡單而甜美。謝謝 – jforjs