Reputation: 10139
I want to be able to draw some basic vector shapes onto a HTML5 Canvas element.
The user should be able to use the mouse to directly draw any of these:
Square
Circle
Polygon
Onto the Canvas - these will later be used for hotspots on an image.
It is important that the user should be able to draw these vector shapes themselves by directly clicking within the canvas.
Is there an existing library that will help with this?
If there is no library, consider that I am an experienced web designer with an excellent knowledge of javascript, but I have very little experience with programming vectors. Where is the best place for me to go to fix this so I can build what I need?
Upvotes: 0
Views: 1629
Reputation: 1224
You can use this little snippet for your first experiments...
for individual circles you must use:
mousedown (getCoordinates) mouseup (getCoordinates)
Calculate the distance between these two points, that´s the radius.
Build an html options list for Square, Circle and Polygon.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Canvas</title>
<style>
canvas{border:1px solid #ccc;}
</style>
</head>
<body>
<canvas id="myCanvas" width="200" height="200"></canvas>
<script>
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
canvas.addEventListener('click', function(evt) {
var mousePos = getMousePos(canvas, evt);
context.beginPath();
context.arc(mousePos.x,mousePos.y,5,0,2*Math.PI);
context.stroke();
}, false);
</script>
</body>
</html>
Upvotes: 1