问题
How to get a sections of a single image using javascript and store it in an array, and later display randomly on html5 canvas.
回答1:
You can use the clipping parameters of the drawImage() method and draw your clipped image onto a dynamically created canvas.
An example could be:
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;
}
This will return a canvas element with the clipped image drawn in already. You can now use the canvas directly to draw it onto another canvas.
Example of usage; in your main code you can do:
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:
....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>
来源:https://stackoverflow.com/questions/21933043/split-an-image-using-javascript