效果如图
绘图依然用前面使用过的Polygon类进行绘图
drawPolygon是复制图形并旋转的函数
make_image是复制图像并进行缩放的函数
二者的思想就是对context绘图环境进行translate scale平移或缩放 ,平移缩放之后再restore进行还原 毫不影响
下面是代码
var canvas=document.getElementById("canvas")
var context=canvas.getContext("2d")
var RECT_width=100
var RECT_height=100;
var Point = function (x, y) {
this.x = x;
this.y = y;
};
var Polygon=function(centerX,centerY,radius,sides,startAngle,strokeStyle,fillStyle,filled){
this.x=centerX;
this.y=centerY;
this.radius=radius;
this.sides=sides;
this.startAngle=startAngle;
this.strokeStyle=strokeStyle;
this.fillStyle=fillStyle;
this.filled=filled;
}
Polygon.prototype={
getPoints:function(){
var points=[];
var angle=this.startAngle||0;
for(var i=0;i<this.sides;i++){
points.push(new Point(this.x+this.radius*Math.cos(angle),this.y-this.radius*Math.sin(angle)))
angle+=2*Math.PI/this.sides
}
return points
},
createPath:function(context){
var points=this.getPoints()
context.beginPath()
context.moveTo(points[0].x,points[0].y);
for(var i=1;i<points.length;i++){
context.lineTo(points[i].x,points[i].y)
}
context.closePath()
},
stroke:function(context){
context.save()
this.createPath(context)
context.strokeStyle=this.strokeStyle;
context.stroke();
context.restore();
},
fill:function(context){
context.save();
context.fillStyle=this.fillStyle;
this.createPath(context)
context.fill()
context.restore()
},
move: function (x, y) {
this.x = x;
this.y = y;
}
}
var test=new Polygon(150,150,20,4,0,"red","red")
test.fill(context)
function drawPolygon(polygon,angle,color){
var tx=polygon.x
var ty=polygon.y
context.save()
context.translate(tx,ty)
if(angle){
context.rotate(angle)
}
polygon.x=0
polygon.y=0
polygon.fillStyle=color
polygon.fill(context)
context.restore()
}
drawPolygon(test,130,"blue")
function make_image(polygon){
context.save()
context.translate(100,canvas.height/2)
context.scale(2,2)
polygon.fill(context)
context.restore()
}
make_image(test)