JSFiddle - React, Tailwind, and code Playground
by blindman67
HTML
<canvas id="can" width="400" height="400" style="width:400px;height:400px;"></canvas>
JavaScript
var canvasMouseCallBack;
var mouse = {
x:0,
y:0
};
function mouseMove(event){
// get new mouse positions
mouse.x = event.offsetX;
mouse.y = event.offsetY;
if(mouse.x === undefined){ // if firefox
mouse.x = event.clientX;
mouse.y = event.clientY;
}
if(canvasMouseCallBack){
canvasMouseCallBack(mouse.x,mouse.y);
}
}
var canV = document.getElementById("can");
canV.addEventListener('mousemove',mouseMove);
var ctx = canV.getContext("2d");
// Assume ctx is canvas 2D Context and ready to render to
var cx = ctx.canvas.width / 2;
var cy = ctx.canvas.height / 2;
var font = "Verdana"; // font for annotation
var fontSize = 12; // font size for annotation
var angleWind = 0;
var lastAng;
function getScale(){ // gets the current transform scale
// assumes transform is square. ie Y and X scale are equal and at right angles
var a = ctx.currentTransform.a; // get x vector from current trans
var b = ctx.currentTransform.b;
return Math.sqrt(a * a + b * b); // work out the scale
}
// Code is just a quicky to annotate line and aid visualising current problem
// Not meant for anything but this example. Only Tested on Chrome
// This is needed as the canvas text API can not handle text at very small scales
// so need to draw at unit scale over existing transformation
function annotateLine(pA, pB, text, colour, where){
var scale, size, ang, xdx, xdy, len, textStart, ox, oy;
scale = getScale(); // get the current scale
size = fontSize; // get font size
// use scale to create new origin at start of line
ox = ctx.currentTransform.e + pA.x * scale ;
oy = ctx.currentTransform.f + pA.y * scale;
// get direction of the line
ang = Math.atan2(pB.y - pA.y, pB.x - pA.x);
xdx = Math.cos(ang); // get the new x vector for transform
xdy = Math.sin(ang);
// get the length of the new line to do annotation positioning
len = Math.sqrt( Math.pow(pB.y...