效果如图
代码如下
Polygon是一个基础的生成多边形的类,接我上节文章
var canvas=document.getElementById("canvas");
var context=canvas.getContext("2d");
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(){
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.save()
this.createPath()
context.strokeStyle=this.strokeStyle;
context.stroke();
context.restore();
},
fill:function(){
context.save();
context.fillStyle=this.fillStyle;
this.createPath()
context.fill()
context.restore()
},
move: function (x, y) {
this.x = x;
this.y = y;
}
}
Math.abs是求绝对值
Math.sqrt是开平方
这俩作用是利用勾股定理求半径,然后Polygon需要用半径画多边形
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d'),
eraseAllButton = document.getElementById('eraseAllButton'),
strokeStyleSelect = document.getElementById('strokeStyleSelect'),
startAngleSelect = document.getElementById('startAngleSelect'),
fillStyleSelect = document.getElementById('fillStyleSelect'),
fillCheckbox = document.getElementById('fillCheckbox'),
editCheckbox = document.getElementById('editCheckbox'),
sidesSelect = document.getElementById('sidesSelect')
var edite=false
var mousedown={}//记录鼠标按下起始点
var imageData1=null;
var mouseIn=null;//记录鼠标是否按了下去
var line_list={} //记录鼠标的终点
function saveImage(){ //储存此刻画布数据
imageData1= context.getImageData(0,0,canvas.width,canvas.height)
}
function loadingImage(){ //导入画布数据
context.putImageData(imageData1,0,0)
}
editCheckbox.onchange=function(){
if(this.checked){
console.log("进入编辑模式")
edite=true
}else{
console.log("进入画图模式")
edite=false
}
}
function windowToCanvas(event){ //算出你点击在canvas画布的坐标 并返回
var rect=canvas.getBoundingClientRect()
return {
x:event.clientX-rect.left,
y:event.clientY-rect.top
}
}
function line_width(){
var x_width=Math.abs(line_list.x-mousedown.x)
var y_width=Math.abs(line_list.y-mousedown.y)
return Math.sqrt(x_width*x_width+y_width*y_width)
}
canvas.onmousedown=function(event){
saveImage()
var some=windowToCanvas(event)
mousedown.x=some.x;
mousedown.y=some.y
mouseIn=true
}
canvas.onmousemove=function(event){
if(mouseIn){//如果按下鼠标并拖行
loadingImage()
line_list=windowToCanvas(event)
context.beginPath()
var r=line_width()
var wangxu=new Polygon(mousedown.x,mousedown.y,r,sidesSelect.value,0,"red","red")
wangxu.fill()
}
}
canvas.onmouseup=function(){
mouseIn=false //鼠标抬起来了
}