canvas基本操作

canvas基本操作

/**
 * @description: 初始化画布
 * @param {*} id 画布标签的id
 * @return {*} void
 */
initCanvas(id) {
  let canvas = document.getElementById(id);
  if (canvas.getContext) {
    //检测浏览器是否兼容
    let ctx = canvas.getContext("2d"); //你的canvas代码在这里
    return ctx;
  }
  return null;
},
/**
 * @description:绘制矩形
 * @param {*} x 起始x坐标
 * @param {*} y 起始y坐标
 * @param {*} r_width 矩形宽
 * @param {*} r_height 矩形高
 * @param {*} line_width 边框宽度
 * @return {*} void
 */
drawRect(x, y, r_width, r_height, line_width) {
  let ctx = this.initCanvas();
  ctx.fillStyle = "#2E81CE";
  ctx.strokeStyle = "#2E81CE";
  ctx.lineWidth = line_width;
  ctx.fillRect(x, y, r_width, r_height);
  ctx.strokeRect(x, y, r_width, r_height);
},
/**
 * @description:画圆
 * @param {*} x
 * @param {*} y
 * @param {*} radius 半径
 * @param {*} startAngle 开始弧度
 * @param {*} endAngle 结束弧度
 * @param {*} anticlockwise true顺时针绘制,false逆时针绘制
 * @return {*} void
 */
drawCircle(x, y, radius, startAngle, endAngle, anticlockwise) {
  let canvas = this.initCanvas();
  canvas.fillStyle = "#2E81CE";
  canvas.beginPath();
  canvas.arc(x, y, radius, startAngle, endAngle, anticlockwise);
  canvas.closePath();
  canvas.fill();
},
/**
 * @description: 画直线
 * @param {*} x 起始横坐标
 * @param {*} y 起始纵坐标
 * @param {*} x_end 终止横坐标
 * @param {*} y_end 终止纵坐标
 * @param {*} line_width 线的宽度
 * @return {*} void
 */
drawLine(x, y, x_end, y_end, line_width) {
  var canvas = this.initCanvas();
  canvas.strokeStyle = "red";
  canvas.lineWidth = line_width;
  canvas.beginPath();
  canvas.moveTo(x, y); //设置起点
  canvas.lineTo(x_end, y_end); //设置终点
  canvas.closePath();
  canvas.stroke(); //画线
},
posted @ 2021-01-06 15:29  沐雨辰沨  阅读(277)  评论(0)    收藏  举报