SOURCE

console 命令行工具 X clear

                    
>
console
// .js
const canvas = document.getElementById('tutorial');
// ctx就是我的纸了
const ctx = canvas.getContext('2d');
// 准备一下我的笔(就拿个红色吧~)
ctx.strokeStyle = 'red';
// 填充颜色
ctx.fillStyle = 'red';
function onLoad() {
  // 设置canvas为图片大小
  canvas.height = img.height;
  canvas.width = img.width;
  // 绘制图片 (0,0)开始1:1绘制img
  // ctx.drawImage(img,x,y,width,height);
  ctx.drawImage(img, 0, 0, img.width, img.height);
}
canvas.addEventListener("mousedown", onMouseDown);
canvas.addEventListener("mousemove", onMouseMove);

function getPointOnCanvas() {
  // canvas相对于视窗的位置集合
  const rect = canvas.getBoundingClientRect();
  return {
    x: x - rect.left * (canvas.width / rect.width),
    y: y - rect.top * (canvas.height / rect.height)
  }
}

function onMouseDown(event) {
  var x = event.pageX;
  var y = event.pageY;
  // 获取起点
  startPoint = getPointOnCanvas(canvas, x, y);

  ctx.beginPath();
  ctx.moveTo(startPoint.x, startPoint.y);
}

function getRectParam(curPoint) {
  const _w = curPoint.x - startPoint.x;
  const _h = curPoint.y - startPoint.y;
  const _startPoint = _w < 0 || _h < 0 ? curPoint : startPoint;
  return {
    _startPoint,
    _w,
    _h
  };
};

function drawRect() {
  // 获取绘制矩形需要的参数
  const newRect = getRectParam(curPoint)
  // 绘制矩形
  ctx.beginPath();
  ctx.rect(
    newRect._startPoint.x,
    newRect._startPoint.y,
    Math.abs(newRect._w),
    Math.abs(newRect._h)
  );
  ctx.stroke();
}

function mousemove(event) {
  const x = event.pageX;
  const y = event.pageY;
  // 获取
  const curPoint = getPointOnCanvas(canvas, x, y);
  drawRect();
};
const dataURL = canvas.toDataURL('image/png')
<img
  style={{ width: 100px, height: 100px }}
  src="https://t7.baidu.com/it/u=4162611394,4275913936&fm=193&f=GIF"
  onLoad={onLoad}
/>
<canvas id="tutorial"></canvas>