console
const canvas = document.getElementById('tutorial');
const ctx = canvas.getContext('2d');
ctx.strokeStyle = 'red';
ctx.fillStyle = 'red';
function onLoad() {
canvas.height = img.height;
canvas.width = img.width;
ctx.drawImage(img, 0, 0, img.width, img.height);
}
canvas.addEventListener("mousedown", onMouseDown);
canvas.addEventListener("mousemove", onMouseMove);
function getPointOnCanvas() {
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>