最近项目上要实现一个类似像素风格的画板,可以像素小格子可以擦除,框选变色,可以擦出各种图形,这样一个小项目看似简单,包含的东西还真不少。
绘制像素格子
我们先定义像素格子类
Pixel = function (option) {
this.x = option.x;
this.y = option.y;
this.shape = option.shape;
this.size = option.size || 8;
}
x和y表示中心点坐标,一开始我是这么做的,先定义路径
createPath: function (ctx) {
if (this.shape === 'circle') {
this.createCircle(ctx);
} else if (this.shape === 'rect') {
this.createRect(ctx);
} else {
this.createCircle(ctx);
}
},
createCircle: function (ctx) {
var radius = this.size / 2;
ctx.arc(this.x,this.y,radius,0,Math.PI*2);
},
createRect: function (ctx) {
var points = this.getPoints();
points.forEach(function (point, i) {
ctx[i == 0 ? 'moveTo' : 'lineTo'](point.x, point.