JSFiddle - React, Tailwind, and code Playground
HTML
<canvas id="myCanvas" width="640" height="480"></canvas>
<div id="debug"></div>
CSS
canvas {
display: block;
border: 1px solid;
}
JavaScript
var cvs = document.getElementById("myCanvas");
var ctx = cvs.getContext("2d");
var debug = document.getElementById("debug");
// points
var a = {x: 100, y: 100};
var b = {x: 10, y: 110};
var c = {x: 100, y: 100};
var d = {x: 150, y: 10};
// vectors
var getVector = function (p1, p2) {
return {
x: p2.x - p1.x,
y: p2.y - p1.y
};
};
var dotProduct = function(v1, v2) {
return v1.x * v2.x + v1.y * v2.y;
};
var crossProduct = function(v1, v2) {
return v1.x * v2.y - v1.y * v2.x;
};
var getAngle = function (v1, v2) {
var dot = dotProduct(v1, v2);
var cross = crossProduct(v1, v2);
return Math.atan2(cross, dot);
};
// draw
var drawPoint = function (ctx, color, p) {
ctx.beginPath();
ctx.arc(p.x, p.y, 5, 0, 2 * Math.PI);
ctx.fillStyle = color;
ctx.fill();
};
var drawVector = function(ctx, color, p1, p2) {
ctx.beginPath();
ctx.moveTo(p1.x, p1.y);
ctx.lineTo(p2.x, p2.y);
ctx.strokeStyle = color;
ctx.stroke();
};
cvs.addEventListener("mousemove", function(e) {
var cvsRect = cvs.getBoundingClientRect();
d = {
x: e.clientX - cvsRect.left,
y: e.clientY - cvsRect.top
};
ctx.clearRect(0, 0, cvs.width, cvs.height);
drawVector(ctx, "#cc0000", a, b);
drawVector(ctx, "#00cc00", c, d);
//drawPoint(ctx, "#cc0000", a);
//drawPoint(ctx, "#cc0000", b);
//drawPoint(ctx, "#00cc00", c);
//drawPoint(ctx, "#00cc00", d);
var v1 = getVector(a, b);
var v2 = getVector(c, d);
var alpha = getAngle(v1, v2);
debug.innerHTML = "Угол в градусах = " + (alpha * 180 / Math.PI);
}, false);