Last active
September 26, 2015 10:43
-
-
Save andrew-pa/63dc7e11d5d3dec0027a to your computer and use it in GitHub Desktop.
Simple quad with movable points
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html> | |
<head> | |
<title>Vector Drawing</title> | |
<script> | |
var canvas, cnt; | |
var vdw = []; | |
var scl = 200, ofs = 200; | |
var moving_dot = -1; | |
var selected_dot = -1; | |
function mousepos(evt) { | |
var rect = canvas.getBoundingClientRect(); | |
return [ ((evt.clientX - rect.left) - ofs)/scl, ((evt.clientY - rect.top)-ofs)/scl ]; | |
} | |
function init() { | |
canvas = document.getElementById('cnvs'); | |
cnt = canvas.getContext('2d'); | |
cnt.strokeStyle = 'black'; | |
vdw[vdw.length] = [0, 0]; | |
vdw[vdw.length] = [1.5, 0]; | |
vdw[vdw.length] = [1, 1]; | |
vdw[vdw.length] = [0, 1.5]; | |
vdw[vdw.length] = vdw[0]; | |
setInterval(animLoop, 16); | |
canvas.addEventListener('contextmenu', function(evt) { evt.preventDefault(); }, false); | |
canvas.addEventListener('mousedown', function(evt) { | |
var mp = mousepos(evt); | |
for(var i = 0; i < vdw.length-1; ++i) { | |
var d = vdw[i]; | |
var l = Math.abs(((d[0])-mp[0]) * ((d[1])-mp[1])); | |
if(l < 0.01) { | |
if(evt.which == 1) moving_dot = i; | |
else if(evt.which == 3) selected_dot = i; | |
break; | |
} | |
} | |
}); | |
canvas.addEventListener('mousemove', function(evt) { | |
vdw[moving_dot] = mousepos(evt); | |
if(moving_dot == 0) vdw[vdw.length-1] = mousepos(evt); | |
}); | |
canvas.addEventListener('mouseup', function(evt) { | |
moving_dot = -1; | |
}); | |
window.addEventListener('keydown', function(evt) { | |
if(selected_dot > -1) { | |
var x = (vdw[selected_dot][0] + vdw[selected_dot+1][0])/2; | |
var y = (vdw[selected_dot][1] + vdw[selected_dot+1][1])/2; | |
vdw.splice(selected_dot, 0, [x,y]); | |
} | |
}); | |
} | |
var t = 0; | |
function animLoop() { | |
t += 16/1000; | |
cnt.clearRect(0, 0, canvas.width, canvas.height); | |
cnt.beginPath(); | |
cnt.moveTo(vdw[0][0]*scl + ofs, vdw[0][1]*scl + ofs); | |
for(var i = 1; i < vdw.length; ++i) { | |
cnt.lineTo(vdw[i][0]*scl + ofs,vdw[i][1]*scl + ofs); | |
} | |
cnt.lineTo(vdw[0][0]*scl + ofs, vdw[0][1]*scl + ofs); | |
cnt.lineWidth = 2; | |
cnt.stroke(); | |
for(var i = 0; i < vdw.length-1; ++i) { | |
if(selected_dot == i) cnt.fillStyle = 'orange'; | |
else cnt.fillStyle = 'blue'; | |
cnt.beginPath(); | |
cnt.arc(vdw[i][0]*scl + ofs, vdw[i][1]*scl + ofs, 5, 0, 2*Math.PI, false); | |
cnt.fill(); | |
} | |
} | |
</script> | |
</head> | |
<body onload="init()"> | |
<canvas id="cnvs" width="800" height="600"></cavas> | |
</body> | |
</body> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment