Skip to content

Instantly share code, notes, and snippets.

@macisi
Created December 10, 2013 08:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save macisi/7887505 to your computer and use it in GitHub Desktop.
Save macisi/7887505 to your computer and use it in GitHub Desktop.
canvas { border: 0 solid #000;}
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<canvas id="C" width="500" height="500"></canvas>
</body>
</html>
var canvas = document.querySelector("#C");
var ctx = canvas.getContext("2d");
//console.log(canvas);
canvas.style.position = "absolute";
canvas.style.left = 0;
canvas.style.top = 0;
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var events = {
"mousedown": onMousedown,
"mouseup": onMouseup,
"mousemove": onMousemove
};
Object.keys(events).forEach(function(event){
canvas.addEventListener(event, events[event], false);
});
var mousedown = false;
// ctx.shadowBlur = 10;
// ctx.shadowColor = "rgba(0, 0, 0, 1)";
// ctx.lineWidth = 10;
// ctx.lineJoin = ctx.lineCap = 'round';
var points = [];
var lastPoint;
function drawNormal(pos0, pos1){
var middlePoint = {x: (pos0.x + pos1.x) / 2, y: (pos0.y + pos1.y) / 2};
var dist = Math.sqrt(Math.pow(middlePoint.x - pos0.x, 2) + Math.pow(middlePoint.y - pos0.y, 2));
var cos = (middlePoint.y - pos0.y) / dist;
var sin = (middlePoint.x - pos0.x) / dist;
var l = 10;
var p1 = {x: middlePoint.x + l * cos, y: middlePoint.y - l * sin};
var p2 = {x: middlePoint.x - l * cos, y: middlePoint.y + l * sin};
ctx.beginPath();
ctx.moveTo(p1.x, p1.y);
ctx.lineTo(p2.x, p2.y);
ctx.stroke();
ctx.closePath();
}
function onMousedown(e){
ctx.beginPath();
lastPoint = {x: e.offsetX, y: e.offsetY};
ctx.moveTo(e.offsetX, e.offsetY);
mousedown = true;
}
function onMouseup(e){
mousedown = false;
points.length = 0;
}
function onMousemove(e){
if (!mousedown) return;
var point;
points.push({x: e.offsetX, y: e.offsetY});
if (points.length > 2) {
point = points.shift();
// ctx.strokeRect(point.x, point.y, e.offsetX - point.x, e.offsetY - point.y);
drawNormal({x: e.offsetX, y: e.offsetY}, point);
}
ctx.moveTo(lastPoint.x, lastPoint.y);
ctx.lineTo(e.offsetX, e.offsetY);
ctx.stroke();
lastPoint = {x: e.offsetX, y: e.offsetY};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment