2014-02-21 298 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