You can slice and space an image apart using the canvas drawImage
function
All the work is done by the context.drawImage
function using some extra parameters
drawImage
is able to clip a portion of the source image and draw it on the canvas
BTW, drawImage
is also able to simultaneously scale that clipped portion.
Here are the arguments to allow drawImage
to slice the source image:
- The source image
- X position on the source image where clipping will start
- Y position on the source image where clipping will start
- Width of the source image to clip
- Height of the the source image to clip
- X position on the canvas to place the clipped sub-image
- Y position on the canvas to place the clipped sub-image
- The scaled width of the clipped image to be drawn on the canvas
- The scaled height of the clipped image to be drawn on the canvas
And here’s how to use drawImage to slice the source image into 3x3 cells with 10px spacing
context.drawImage(
img, // the source image
0,0, // get the image starting at it's 0,0 position
img.width, // grab the entire width of the image
img.height // grab the entire height of the image
x*img.width/3+10, // make 3 image "columns" with 10px spacing
x*img.height/3+10, // make 3 image "rows" with 10px spacing
img.width/3, // each image column is 1/3 of the original image
img.height/3 // each image row is 1/3 of the original image
);
Here’s code and a Fiddle: http://jsfiddle.net/m1erickson/m89Gg/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var image=new Image();
image.onload=function(){
slice(image);
}
image.src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/sky-bg2.jpg";
function slice(img){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var w=img.width; // original image width
var h=img.height; // original image height
var rows=3; // # of rows
var cols=3; // # of columns
var cw=w/rows; // cell width
var ch=h/cols; // cell height
var scale=3; // also, scale the image down
var spacing=5; // spacing between cells
// set the canvas width to accommodate
// sliced/space/scaled image
canvas.width=w/scale+spacing*2;
canvas.height=h/scale+spacing*2;
ctx.clearRect(0,0,canvas.width,canvas.height);
for(var y=0;y<3;y++){
for (var x=0;x<3;x++){
ctx.drawImage(img,x*cw,y*ch,cw,ch,
x*(cw/scale+spacing),y*(ch/scale+spacing),cw/scale,ch/scale)
}
}
ctx.stroke()
}
}); // end $(function(){});
</script>
</head>
<body>
<canvas id="canvas" width=300 height=300></canvas>
</body>
</html>