Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Raphael.JS: Draw Circle Based on Mouse Move

0.00/5 (No votes)
29 Jan 2015 1  
Raphael.JS: Draw circle based on mouse move

Raphael is a JavaScript library for drawing vector graphics on the web. Here I have created a small JavaScript program to draw a circle based on mouse move. You just need to include JQuery and Raphael JavaScript libraries. Then create an HTML div to use as drawing canvas and copy the JavaScript from here and cheer.

HTML

<div id="Div1" style="width: 600px; 
height: 400px; border: 4px dotted #ccc; 
cursor: crosshair;">
</div>

JavaScript

var size = 3,
 color = "Blue",
 fill = "F",
 x2 = 0,
 y2 = 0;

$(document).ready(function () {
 var paper = Raphael("canvas");
 var shap;
 $("#canvas").mousedown(function (e) {
 if (e.offsetX) {
 x1 = e.offsetX;
 y1 = e.offsetY;
 }
 else if (e.layerX) {
 x1 = e.layerX;
 y1 = e.layerY;
 }

 shap = circle(x1, y1, x1, y1, paper);

 $("#canvas").bind('mousemove', function (e) {
 if (e.offsetX) {
 x2 = e.offsetX;
 y2 = e.offsetY;
 }
 else if (e.layerX) {
 x2 = e.layerX;
 y2 = e.layerY;
 }
 shap.updateEnd(x2, y2);
});
 $("#canvas").mouseup(function (e) {
 $("#canvas").unbind('mousemove');
 });
 });
 });
 function circle(x1, y1, x2, y2, raphael) {

 var center = {
 x: (x1+x2)/2,
 y: (y1+y2)/2
 };

 var radius = {

 h: Math.sqrt((y2 - y1) * (y2 - y1))/2,
 w: Math.sqrt((x2 - x1) * (x2 - x1))/2

 };
 var getPath = function () {

 return [["M", center.x, center.y], ["m", 0, -radius.h], 
 ["a", radius.w, radius.h, 0, 1, 1, 0, 2 * radius.h], 
 ["a", radius.w, radius.h, 0, 1, 1, 0, -2 * radius.h], 
 ["z"]];

 };

 var redraw = function () {

 node.attr("path", getPath());

 if (fill == "T")
 node.attr(
 {
 'fill': color,
'stroke-width': 0
 });
 else {
 node.attr(
 {
 stroke: color,
 'stroke-width': size
 });
 }
 };
 var node = raphael.path(getPath()); 
 return {
 updateStart: function (x, y) {
 center.x = (x1 + x) / 2;
 center.y = (y1 + y) / 2;
 radius.w = Math.sqrt((x - x1) * (x - x1))/2;
 radius.h = Math.sqrt((y - y1) * (y - y1))/2;
 redraw();
 return this;
 },
 updateEnd: function (x, y) {
 center.x = (x1 + x) / 2;
 center.y = (y1 + y) / 2;
 radius.w = Math.sqrt((x - x1) * (x - x1))/2;
 radius.h = Math.sqrt((y - y1) * (y - y1))/2;
 redraw();
 return this;
 }
 };
};

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here