# canvas像素画板

3,409

#### 绘制像素格子

``````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;
},

createRect: function (ctx) {
var points = this.getPoints();
points.forEach(function (point, i) {
ctx[i == 0 ? 'moveTo' : 'lineTo'](point.x, point.y);
})
ctx.lineTo(points[0].x, points[0].y);
},
``````

``````draw: function (ctx) {
ctx.save();
ctx.lineWidth=this.lineWidth;
ctx.strokeStyle=this.strokeStyle;
ctx.fillStyle=this.fillStyle;
ctx.beginPath();
this.createPath(ctx);
ctx.stroke();
if(this.isFill){ctx.fill();}
ctx.restore();
}
``````

``````for (var i = stepX + .5; i < canvas.width; i+=stepX) {
for (var j = stepY + .5; j < canvas.height; j+=stepY) {
var pixel = new Pixel({
x: i,
y: j,
shape: 'circle'
})
box.push(pixel);
pixel.draw(ctx);
}
}
``````

``````//定义像素的位置
for (var i = stepX + .5; i < canvas.width; i+=stepX) {
for (var j = stepY + .5; j < canvas.height; j+=stepY) {
var pixel = new Pixel({
x: i,
y: j,
shape: 'circle'
})
box.push(pixel);
}
}

//批量绘制
console.time('time');
ctx.beginPath();
for (var c = 0; c < box.length; c++) {
var circle = box[c];
ctx.moveTo(circle.x + 3, circle.y);
circle.createPath(ctx);
}
ctx.closePath();
ctx.stroke();

console.timeEnd('time');
``````

#### 像素网格交互

##### 获取鼠标移动路径下的网格

``````function sqr(x) { return x * x }

function dist2(p1, p2) { return sqr(p1.x - p2.x) + sqr(p1.y - p2.y) }

function distToSegmentSquared(p, v, w) {
var l2 = dist2(v, w);
if (l2 == 0) return dist2(p, v);
var t = ((p.x - v.x) * (w.x - v.x) + (p.y - v.y) * (w.y - v.y)) / l2;
if (t < 0) return dist2(p, v);
if (t > 1) return dist2(p, w);
return dist2(p, {
x: v.x + t * (w.x - v.x),
y: v.y + t * (w.y - v.y)
});
}

/**
* @description 计算线段与圆是否相交
* @param {x: num, y: num} p 圆心点
* @param {x: num, y: num} v 线段起始点
* @param {x: num, y: num} w 线段终点
*/
function distToSegment(p, v, w) {
var offset = pathHeight;
var minX = Math.min(v.x, w.x) - offset;
var maxX = Math.max(v.x, w.x) + offset;
var minY = Math.min(v.y, w.y) - offset;
var maxY = Math.max(v.y, w.y) + offset;

if ((p.x < minX || p.x > maxX) && (p.y < minY || p.y > maxY)) {
return Number.MAX_VALUE;
}

return Math.sqrt(distToSegmentSquared(p, v, w));
}
``````