Writing in the front

Today, I received a demand: during offline quality inspection, we conducted a comparative test according to the uploaded picture and the real object. We need to dynamically mark the spots with defects or stains on the picture for the convenience of subsequent process detection and recording. I think the canvas I used before can realize this function. Without further ado, let’s get to know canvas.

Canvas Self Introduction

Hi, I’m Canvas, I can let you draw with JavaScript on canvas tag. In addition, animation, game graphics, data visualization, photo processing and real-time video processing are not difficult for me

One, my compatibility (how big the heart, how big the stage)

You Can check compatibility on Can I Use before using the front-end technology.

What can I do ** With great power comes great responsibility

I’m going to tell you how I work, and I’m going to start simple.

Pick up a pen and paper

// .html
<canvas id="tutorial" width="150" height="150"></canvas>

// .js
const canvas = document.getElementById('tutorial');
// CTX is my paper
const ctx = canvas.getContext('2d');
// Get my pen ready.
ctx.strokeStyle = 'red';
// Fill the color
ctx.fillStyle = 'red';
Copy the code

2. Basic usage

I’ve come up with some ideas that you can use much faster

  • Line drawing

ctx.beginPath();
ctx.lineWidth="5";
ctx.strokeStyle="red"; // Red path
ctx.moveTo(0.75);
ctx.lineTo(250.75);
ctx.stroke(); // Draw

ctx.beginPath();
ctx.strokeStyle="blue"; // Blue path
ctx.moveTo(50.0);
ctx.lineTo(150.130);
ctx.stroke(); // Draw
Copy the code
  • Draw a circle

ctx.beginPath();
// ctx.arc(x,y,r,sAngle,eAngle,counterclockwise);
// x: the x-coordinate of the center of the circle.
// y: the y coordinate of the center of the circle.
// r: radius of the circle.
// sAngle: initial Angle, measured in radians. The three o 'clock position of the circle of the arc is 0 degrees.
// eAngle: end Angle, in radians
// Counterclockwise: Optional. Specifies whether to draw counterclockwise or clockwise. False = clockwise, true = counterclockwise.
ctx.arc(100.75.50.0.2*Math.PI);
ctx.stroke();
Copy the code
  • Draw a frame

// x: the x-coordinate of the upper left corner of the rectangle
// y: y coordinates of the upper left corner of the rectangle
// width: width of the rectangle, in pixels
// height: height of the rectangle, in pixels
// Fill the rectangle
ctx.fillRect(x: 20.y: 20.width: 150.height: 100);
// No fill rectangle
ctx.strokeRect(20.20.150.100);
Copy the code

Ok, the above is my basic skills, if you are interested, you can see all my skills oh ~

Going back to requirements, how should we developers use Canvas to fulfill requirements?

practice

Combined with Canvas skills, the design idea is as follows:

  • Get the image of the adaptation
  • Convert picture: Draw canvas 1:1 according to picture
  • Dynamic editing: mark operations on the canvas, can be added, deleted and changed
  • Generate picture: Convert canvas to picture
1. Get and convert imagesdrawImage
<img
  style={{ width: 100px, height: 100px }}
  src="https://test.jpg"
  onLoad={onLoad}
/>
<canvas></canvas>

function onLoad() {
  // Set canvas to image size
  canvas.height = img.height;
  canvas.width = img.width;
  // draw the image (0,0)
  // ctx.drawImage(img,x,y,width,height);
  ctx.drawImage(img, 0.0, img.width, img.height);
}
Copy the code
2. Edit function (box selection function is mainly realized here)
canvas.addEventListener("mousedown", onMouseDown);
canvas.addEventListener("mousemove", onMouseMove);

function getPointOnCanvas() {
  // Set of canvas positions relative to the window
  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;
  // Get the starting point
  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() {
  // Get the parameters needed to draw the rectangle
  const newRect = getRectParam(curPoint)
  // Draw a rectangle
  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;
  / / to get
  const curPoint = getPointOnCanvas(canvas, x, y);
  drawRect();
};
Copy the code
3. Canvas to picture
const dataURL = canvas.toDataURL('image/png')
Copy the code

This is part of the code to see the editing effect:

At present, the requirements have been put online smoothly, and the feedback from quality inspectors is very good.

Write in the back

I hope this article will bring you a way of thinking about front-end image processing. Interested students can try other functions of Canvas, such as: add text, edit withdraw and so on.

In the coming days, there will be a trash-pit tour of three no-project reconstructions and cross-application drag-and-drop capability practices. Progress a little bit every day, quality change from paying attention to the big round FE start!