我需要在用户浏览器中将图像水平划分2行,垂直划分2行。这样图像就有9个部分。
通过绘制线条或将9个部分分开来做到这一点。
我知道Raphael和paper.js但也许可以在没有其他框架的情况下完成(canvas html5和html4 JS)。
如果你有一个方法,使用它也能够像分裂蛋糕一样分成4圈吗?
答案 0 :(得分:2)
您可以使用画布drawImage
功能
所有工作都由context.drawImage
函数使用一些额外参数
drawImage
能够剪切部分源图像并将其绘制在画布上
BTW,drawImage
也可以同时缩放该剪辑部分。
以下是允许drawImage
切片源图像的参数:
以下是如何使用drawImage将源图像切割成间距为10px的3x3单元格
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
);
这是代码和小提琴: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>