(十八)原生js案例之cvs签字板

canvas日常业务比较少接触,就这么说吧,虽然偏门,但一旦用起来,没有足够的只是储备,你根本玩不转!!赶紧学习吧

实现效果请添加图片描述

canvas 的特性

  • 1.canvas 是一个矩形区域,可以控制其每一像素
  • 2.canvas 的默认大小是 300*150,可以通过 css 控制其大小
  • 3.canvas 标签中可以写 js 代码,直接操作 canvas 元素

canvas 的基本使用

drawRect();
function drawRect() {
  ctx.fillStyle = "red";
  ctx.fillRect(50, 50, 100, 100);
  //带边框处理边框变粗的代码
  ctx.strokeRect(50.5, 50.5, 100, 100);
}
  • 带边框处理边框变粗的代码,及描边和填充先后顺序

在这里插入图片描述

drawRect();
function drawRect() {
  ctx.fillStyle = "red";
  ctx.strokeStyle = "blue";
  ctx.lineWidth = 10;

  ctx.strokeRect(50.5, 50.5, 100, 100);
  ctx.fillRect(50, 50, 100, 100);

  ctx.fillRect(250, 50, 100, 100);
  ctx.strokeRect(250.5, 50.5, 100, 100);
}
  • lineJoin 属性
ctx.lineJoin = "miter"; //默认
ctx.lineJoin = "round"; //圆角
ctx.lineJoin = "bevel"; //斜角
  • lineCap 属性
    在这里插入图片描述
ctx.save();
//默认值buff
ctx.lineCap = "round";
ctx.moveTo(100, 100);
ctx.lineTo(250, 300);

ctx.stroke();
ctx.restore();
ctx.save();
ctx.lineCap = "square"; //高度多出来的部分,是lineWidth的宽度一般
ctx.moveTo(200, 100);
ctx.lineTo(350, 300);

ctx.stroke();
ctx.restore();
  • save() 和 restore() 属性

    在这里插入图片描述

window.onload = function () {
  var canvas = document.getElementById("mycanvas");
  var ctx = canvas.getContext("2d");

  ctx.save();
  ctx.strokeStyle = "red";
  ctx.beginPath();
  ctx.rect(100, 100, 200, 200);
  ctx.closePath();
  ctx.stroke();
  ctx.restore();

  ctx.beginPath();
  ctx.rect(300, 100, 200, 200);
  ctx.closePath();
  ctx.stroke();
};

案例实战

window.onload = function () {
  const canvas = document.getElementById("mycanvas");
  const clearBtn = document.getElementById("clear");
  const color = document.getElementById("color");
  const lineWidth = document.getElementById("lineWidth");
  const ctx = canvas.getContext("2d");

  canvas.onmousedown = function (e) {
    var e = e || window.event;
    const x = e.clientX - canvas.offsetLeft;
    const y = e.offsetY - canvas.offsetTop;
    ctx.beginPath();
    ctx.strokeStyle = color.value;
    ctx.lineWidth = lineWidth.value;
    ctx.moveTo(x, y);
    canvas.onmousemove = function (e) {
      var e = e || window.event;
      const x1 = e.clientX - canvas.offsetLeft;
      const y1 = e.offsetY - canvas.offsetTop;
      ctx.lineTo(x1, y1);
      ctx.stroke();
    };
    canvas.onmouseup = function (e) {
      canvas.onmousemove = null;
      ctx.closePath();
    };
  };
  clearBtn.addEventListener("click", function () {
    // 画布清空,此处只能清理rect区域,无法清理path,需要加上ctx.beginPath();
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.beginPath();
  });
};
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值