使用JavaScript分割图像

4
如何使用Javascript获取单个图像的部分并将其存储在数组中,然后随机显示在HTML5画布上。
2个回答

11

您可以使用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;
}

这将返回一个带有已经绘制好的裁剪图像的画布元素。现在,您可以直接使用该画布将其绘制到另一个画布上。

用法示例:在您的主要代码中,您可以这样做:

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());

4

或者您可以使用CSS sprite技术,这样更快更容易。

如果您有一张图片(例如my_Image.gif)并且想要使用此方法仅提取部分内容,则可以将其模拟为DIV元素的背景。请参见下面的代码。

portion1 id参数以下简单地表示“从我的图像中,在左侧(margin-left)和顶部(margin-top)0px的位置切割100px宽度和100px高度”

portion2 id参数以下简单地表示“从我的图像中,在左侧(margin-left)-91px和顶部(margin-top)0px的位置切割100px宽度和100px高度”

通过简单操作像素,您可以从任何位置裁剪任何大小的图像。您也可以使用百分比。

注意:在这种情况下,您的图像必须是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>

好主意,简单又甜美。谢谢。 - jforjs

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接