Split an image using javascript

16,832

....Or you can just use the CSS sprite technique which is faster and easier.

If you have an image(my_Image.gif for example) and you intend to extract only a portion using this method, you can simulate the extract as a background of a DIV element . See the code below.

portion1 id parameters below simply say "From my image, slice 100px high and 100px wide from position 0px to the left(margin-left) and 0px to the top(margin-top)"

portion2 id parameters below simply say "From my image, slice 100px high and 100px wide from position -91px to the left(margin-left) and 0px to the top(margin-top)"

With this, you can slice any size from any position by simply manipulating the pixels. You can also use % as well.

Note: Your image must be in gif format in this case and must be residing in the root of your server...

You can use other image extensions...jpeg, png etc.

 <!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>
Share:
16,832
jforjs
Author by

jforjs

Love to eat! Love to code!

Updated on June 05, 2022

Comments

  • jforjs
    jforjs almost 2 years

    How to get a sections of a single image using javascript and store it in an array, and later display randomly on html5 canvas.

  • jforjs
    jforjs almost 9 years
    Nice idea, simple and sweet. Thanks