function: Select a circle or rectangle to paint on a well-defined canvas
Code
<! DOCTYPE html>
<meta charset= "Utf-8"/>
<title></title>
<body>
<div>
<div>
<input type= "Radio" name= "Shap" id= "Circlebutton" checked= "true" >circle</input>
<input type= "Radio" name= "Shap" id= "Rectbutton" >rectangle</input>
<input type= "Color"/>
</div>
<canvas id= "MyCanvas" style= "border:1px solid;" Width= "height=" ></canvas>
</div>
</body>
<script language= "JavaScript" >
var shap = 0; 0 is circle; 1 is Rectangle
var orignalx, orignaly;//the coordinate of mouse down
var lastx, lasty;//the coordinate of last mouse position
var ismousedown = false; Flag of mouse pressing down
var Circlebutton = document.getElementById ("Circlebutton");
var Rectbutton = document.getElementById ("Rectbutton");
var MyCanvas = document.getElementById ("MyCanvas");
var context = Mycanvas.getcontext (' 2d ');
var width = mycanvas.width, height = mycanvas.height;
var data;//storing last canvas ' content
Context.strokestyle = "Red";
context.strokewidth=1;
function Circlebuttonclick () {
Shap = 0;
}
function Rectbuttonclick () {
Shap = 1;
}
function Mycanvasmousedown (event) {
Event.preventdefault ();
if (Event.button = = 0) {
Orignalx = Event.offsetx;
Orignaly = event.offsety;
data = context.getimagedata (0, 0, width, height);
Ismousedown = true;
}
}
function Mycanvasmousemove (event) {
if (Ismousedown) {
Event.preventdefault ();
Context.clearrect (0,0,width,height);
Context.putimagedata (data,0,0);
LASTX = Event.offsetx;
Lasty = event.offsety;
Switch (SHAP) {
Case 0:
Context.beginpath ();
Context.arc (orignalx+ (LASTX-ORIGNALX)/2,orignaly+ (lasty-orignaly)/2,math.abs (LASTX-ORIGNALX)/2,0,Math.PI * 2, true);
Context.stroke ();
Context.closepath ();
Break
Case 1:
Context.strokerect (Orignalx, Orignaly, Lastx-orignalx, lasty-orignaly);
Break
}
}
}
function Mycanvasmouseup (event) {
if (Ismousedown) {
Event.preventdefault ();
Context.clearrect (0,0,width,height);
Context.putimagedata (data,0,0);
LASTX = Event.offsetx;
Lasty = event.offsety;
Switch (SHAP) {
Case 0:
Context.beginpath ();
Context.arc (orignalx+ (LASTX-ORIGNALX)/2,orignaly+ (lasty-orignaly)/2,math.abs (LASTX-ORIGNALX)/2,0,Math.PI * 2, true);
Context.stroke ();
Context.closepath ();
Break
Case 1:
Context.strokerect (Orignalx, Orignaly, Lastx-orignalx, lasty-orignaly);
}
Ismousedown = false;
LASTX = null;
Lasty = null;
}
}
Circlebutton.addeventlistener ("Click", Circlebuttonclick, false);
Rectbutton.addeventlistener ("Click", Rectbuttonclick, false);
Mycanvas.addeventlistener ("MouseDown", Mycanvasmousedown, false);
Mycanvas.addeventlistener ("MouseMove", Mycanvasmousemove, false);
Mycanvas.addeventlistener ("MouseUp", Mycanvasmouseup, false);
</script>
<script language= "JavaScript" >
alert (SHAP);
</script>
JavaScript Simple Canvas Implementation