简体   繁体   中英

How to split a image without using canvas in JavaScript

How do I cut up a image without using the canvas? Lets say I create a image the regular way with new Image() but how do get parts of it without using canvas.getImageData since I want this to work while offline in chrome. I making a small game and I have a spritesheet which I have to cut up and I want this game to work locally, but chrome gets that cross platform error. Is there any other way that I can get parts of the image?
If this is a bad question please dont -rep me, just say so and I'll remove it

Are you having CORS security violations when running offline?

Otherwise, html canvas works fine offline, too :-)

As long as you have access to the spritesheet you can cut it up locally.

If your individual sprites are rectangular, you can use the extended version of drawImage instead of the more involved getImageData

canvas.width=characterWidth    // resize the canvas to the character width 
canvas.height=characterHeight  // resize the canvas to the character height

context.drawImage(
    spritesheet,                      // the spritesheet image
    characterX,characterY,            // the top-left x/y of the character on the spritesheet
    characterWidth,characterHeight,   // the width/height of the character on the spritesheet
    0,0,canvas.width,canvas.height)   // draw the character on the canvas

Then you can do canvas.toDataURL to "cut" that character out and use the dataurl to create an html image object.

[ Addition: use crossOrigin flag to satisfy CORS requirements ]

To satisfy CORS restrictions, you can use the crossOrigin="anonymous" flag on either your html img element or when creating a javascript image object.

Important: Your server must also be configured to deliver images in a CORS compliant way:

http://enable-cors.org/

Here's an example of using to crossOrigin flag to download an image that doesn't taint an html canvas: http://jsfiddle.net/m1erickson/K9C42/

    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");

    var img=new Image();
    img.crossOrigin="anonymous";
    img.onload=start;
    img.src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/flags.jpg";
    function start(){
        canvas.width=100;
        canvas.height=100;
        ctx.drawImage(img,125,10,100,100,0,0,canvas.width,canvas.height);
        var img1=new Image();
        img1.onload=function(){
            document.body.appendChild(img1);
        }
        img1.src=canvas.toDataURL();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM