This article introduces JavaScript code for implementing simple Canvas drawing instances. If you need it, refer to it.
Define variables:
[Javascript]
The Code is as follows:
Var startX;
Var startY;
Var endX;
Var endY;
Var radius;
Var canvas = document. getElementById ("myCanvas ");
Var context = canvas. getContext ("2d ");
Var select = document. getElementsByTagName ("select ");
Var startX;
Var startY;
Var endX;
Var endY;
Var radius;
Var canvas = document. getElementById ("myCanvas ");
Var context = canvas. getContext ("2d ");
Var select = document. getElementsByTagName ("select ");
Function section:
[Javascript]
The Code is as follows:
Window. onload = function (){
Canvas. onmousedown = function (e ){
E = e | event;
StartX = e. clientX;
StartY = e. clientY;
If (select [0]. value = "arc "){
Canvas. onmousemove = moveShowArc;
} Else {
Canvas. onmousemove = moveShowRect;
}
}
Canvas. onmouseup = function (){
Canvas. onmousemove = "";
}
}
Function moveShowRect (e ){
Context. clearRect (0, 0,500,300 );
EndX = e. clientX-startX;
EndY = e. clientY-startY;
Context. beginPath ();
Context. rect (startX, startY, endX, endY );
Context. fillStyle = "# 8ED6FF ";
Context. fill ();
Context. lineWidth = 3;
Context. strokeStyle = "black ";
Context. stroke ();
}
Function moveShowArc (e ){
Context. clearRect (0, 0,500,300 );
EndX = e. clientX-startX;
EndY = e. clientY-startY;
Radius = Math. sqrt (Math. pow (endX, 2) + Math. pow (endY, 2 ));
Context. beginPath ();
Context. arc (startX, startY, radius, 0, 2 * Math. PI, false );
Context. fillStyle = "# 8ED6FF ";
Context. fill ();
Context. lineWidth = 3;
Context. strokeStyle = "black ";
Context. stroke ();
}
Window. onload = function (){
Canvas. onmousedown = function (e ){
E = e | event;
StartX = e. clientX;
StartY = e. clientY;
If (select [0]. value = "arc "){
Canvas. onmousemove = moveShowArc;
} Else {
Canvas. onmousemove = moveShowRect;
}
}
Canvas. onmouseup = function (){
Canvas. onmousemove = "";
}
}
Function moveShowRect (e ){
Context. clearRect (0, 0,500,300 );
EndX = e. clientX-startX;
EndY = e. clientY-startY;
Context. beginPath ();
Context. rect (startX, startY, endX, endY );
Context. fillStyle = "# 8ED6FF ";
Context. fill ();
Context. lineWidth = 3;
Context. strokeStyle = "black ";
Context. stroke ();
}
Function moveShowArc (e ){
Context. clearRect (0, 0,500,300 );
EndX = e. clientX-startX;
EndY = e. clientY-startY;
Radius = Math. sqrt (Math. pow (endX, 2) + Math. pow (endY, 2 ));
Context. beginPath ();
Context. arc (startX, startY, radius, 0, 2 * Math. PI, false );
Context. fillStyle = "# 8ED6FF ";
Context. fill ();
Context. lineWidth = 3;
Context. strokeStyle = "black ";
Context. stroke ();
}