//在canvas中并没有提供虚线的绘制,可以通过如下方式绘制,这种方式的实线和虚线间的距离是相等的
var context = document.getElementById('canvas').getContext('2d'),
moveToFunction = CanvasRenderingContext2D.prototype.moveTo;
CanvasRenderingContext2D.prototype.lastMoveToLocation = {};
CanvasRenderingContext2D.prototype.moveTo = function (x, y) {
moveToFunction.apply(context, [x,y]);
this.lastMoveToLocation.x = x;
this.lastMoveToLocation.y = y;
};
CanvasRenderingContext2D.prototype.dashedLineTo = function (x, y, dashLength) {
dashLength = dashLength === undefined ? 5 : dashLength;
var startX = this.lastMoveToLocation.x;
var startY = this.lastMoveToLocation.y;
var deltaX = x - startX;
var deltaY = y - startY;
var numDashes = Math.floor(Math.sqrt(deltaX * deltaX + deltaY * deltaY) / dashLength);
for (var i=0; i < numDashes; ++i) {
this[ i % 2 === 0 ? 'moveTo' : 'lineTo' ](startX + (deltaX / numDashes) * i, startY + (deltaY / numDashes) * i);//注意这种方法调用方式
}
this.moveTo(x, y);
};
//测试
context.lineWidth = 3;
context.strokeStyle = 'blue';
context.moveTo(20, 20);
context.dashedLineTo(context.canvas.width-20, 20);
//......................下面的程序是画圆角矩形.,通过四次绘制.................................
var context = document.getElementById('canvas').getContext('2d');
function roundedRect(cornerX, cornerY, width, height, cornerRadius) {
if (width > 0) context.moveTo(cornerX + cornerRadius, cornerY);
else context.moveTo(cornerX - cornerRadius, cornerY);
context.arcTo(cornerX + width, cornerY,
cornerX + width, cornerY + height,
cornerRadius);
context.arcTo(cornerX + width, cornerY + height,
cornerX, cornerY + height,
cornerRadius);
context.arcTo(cornerX, cornerY + height,
cornerX, cornerY,
cornerRadius);
if (width > 0) {
context.arcTo(cornerX, cornerY,
cornerX + cornerRadius, cornerY,
cornerRadius);
}
else {
context.arcTo(cornerX, cornerY,
cornerX - cornerRadius, cornerY,
cornerRadius);
}
}
function drawRoundedRect(strokeStyle, fillStyle, cornerX, cornerY, width, height, cornerRadius) {
context.beginPath();
roundedRect(cornerX, cornerY, width, height, cornerRadius);
context.strokeStyle = strokeStyle;
context.fillStyle = fillStyle;
context.stroke();
context.fill();
}
drawRoundedRect('blue', 'yellow', 50, 40, 100, 100, 10);
drawRoundedRect('purple', 'green', 275, 40, -100, 100, 20);
drawRoundedRect('red', 'white', 300, 140, 100, -100, 30);
drawRoundedRect('white', 'blue', 525, 140, -100, -100, 40);