This JavaScript program demonstrates how to draw dots with a mouse on a canvas element. To draw a dot, left-click inside the canvas. To clear the canvas, click the button below it.
<!DOCTYPE html>
<html>
<head>
<title>XoaX.net's Javascript</title>
<script type="text/javascript" src="DrawDots.js"></script>
</head>
<body onload="Initialize()">
<canvas id="idCanvas" width="640" height ="480" style="background-color: #F0F0F0;"></canvas>
<br />
<button onclick="ClearCanvas()">Clear</button>
</body>
</html>var gqContext2D = null;
var gqPoints = [];
function CPoint(dX, dY) {
this.mdX = dX;
this.mdY = dY;
}
function Initialize() {
var qCanvas = document.getElementById("idCanvas");
gqContext2D = qCanvas.getContext("2d");
qCanvas.onmousemove = function(e) {
var qCursor = new CPoint(e.pageX, e.pageY);
GetRelativeCursorLocation(this, qCursor);
RedrawPoints();
gqContext2D.fillStyle = "red";
gqContext2D.beginPath();
gqContext2D.arc(qCursor.mdX, qCursor.mdY, 3, 0, 2.0*Math.PI, true);
gqContext2D.fill();
};
qCanvas.onmouseout = function(e) {
RedrawPoints();
};
qCanvas.onmousedown = function(e) {
var qCursor = new CPoint(e.pageX, e.pageY);
GetRelativeCursorLocation(this, qCursor);
gqPoints.push(qCursor);
};
}
function GetRelativeCursorLocation(qElement, P) {
var dElementOffsetX = 0;
var dElementOffsetY = 0;
do{
dElementOffsetX += qElement.offsetLeft - qElement.scrollLeft;
dElementOffsetY += qElement.offsetTop - qElement.scrollTop;
qElement = qElement.offsetParent
} while(qElement != document.body);
P.mdX -= dElementOffsetX;
P.mdY -= dElementOffsetY;
}
function RedrawPoints() {
gqContext2D.clearRect(0, 0, 640, 480);
gqContext2D.fillStyle = "gray";
for (var i in gqPoints) {
gqContext2D.beginPath();
gqContext2D.arc(gqPoints[i].mdX, gqPoints[i].mdY, 3, 0, 2.0*Math.PI, true);
gqContext2D.fill();
}
}
function ClearCanvas() {
gqPoints = [];
RedrawPoints();
}
© 20072025 XoaX.net LLC. All rights reserved.