如题。封装了几个canvas的函数,有需要的话可以直接用。
直接上代码:
canvas画笔颜色封装:
//画笔颜色
function contextColor(color, context) {
context ? context : context = ctx;
if (color == 1) {
context.strokeStyle = "#00FF00"; //green
} else if (color == 2) {
// context.strokeStyle = "#0000FF"; //blue
context.strokeStyle = "#00FFFF"; //AQUA
} else if (color == 3) {
context.strokeStyle = "#FFFF00"; //yellow
} else if (color >= 4 && color <= 6) {
context.strokeStyle = "#FFFFFF"; //WHITE
} else if (color == 7) {
context.strokeStyle = "#FF0000"; //red
} else if (isNaN) {
context.strokeStyle = color ? color : context.strokeStyle = "#FF00FF"; //FUCHSIA
}
}
canvas画矩形:
//画方框
function drawstrokeRect(x, y, w, h, color) {
contextColor(color);
ctx.strokeRect(x, y, w, h);
}
canvas画虚线:
//虚线直线
function drawDashLine(starX, starY, endX, endY, step) {
ctx.beginPath();
ctx.moveTo(starX, starY);
ctx.setLineDash([step ? step : 5]);
ctx.lineWidth = 2;
ctx.lineTo(endX, endY);
ctx.stroke();
}
canvas画虚线矩形:
//虚线矩形
function drawDashRect(x, y, w, h, color) {
contextColor(color);
drawDashLine(x, y, (x + w), y);
drawDashLine((x + w), y, (x + w), (y + h));
drawDashLine(x, y, x, (y + h));
drawDashLine(x, (y + h), (x + w), (y + h));
}