<pre class="html" name="code"><!DOCTYPE HTML>
<html>
<head>
<meta charset ="utf-8"/>
<title>Canvas Drawing Board</title>
</head>
<body>
<canvas id="canvas" width="600" height="300"></canvas><br>
<br>
<button style="width:80px;background-color:yellow;" οnclick='lineColor="yellow";'>Yellow</button>
<button style="width:80px;background-color:red;" οnclick='lineColor="red";'>Red</button>
<button style="width:80px;background-color:blue;" οnclick='lineColor="blue";'>Blue</button>
<button style="width:80px;background-color:green;" οnclick='lineColor="green";'>Green</button>
<button style="width:80px;background-color:white;" οnclick='lineColor="white";'>White</button><br>
<br>
<button style="width:80px;background-color:silver;" οnclick='linw=4;'>4 pixs</button>
<button style="width:80px;background-color:silver;" οnclick='linw=8;'>8 pixs</button>
<button style="width:80px;background-color:silver;" οnclick='linw=12;'>12 pixs</button><br>
<br>
<button style="width:80px;background-color:black;color:white" οnclick="drawBoard()">Clear</button>
<script type="text/javascript">
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var offsetX = -8; //adjust the contact of the cursor
var offsetY = -8;
//draw the black board
function drawBoard(){
ctx.fillStyle="black";
ctx.fillRect(0,0,600,300);
};
drawBoard();
//mouse down flag
var onoff = false;
var oldx = offsetX;
var oldy = offsetY;
//set line style
var lineColor = "yellow";
var linw = 4;
//add events
canvas.addEventListener("mousemove",draw,true);
canvas.addEventListener("mousedown",down,false);
canvas.addEventListener("mouseup",up,false);
//functions
function down(event){
onoff = true;
oldx = event.pageX+offsetX;
oldy = event.pageY+offsetY;
console.log(oldx + " " + oldy);
ctx.beginPath();
ctx.fillStyle=lineColor;
ctx.arc(oldx,oldy,linw/2,0,360*Math.PI/180,true);
ctx.fill();
}
function up(){
onoff = false;
}
function draw(event){
if(onoff == true){
var newx = event.pageX+offsetX;
var newy = event.pageY+offsetY;
ctx.beginPath();
ctx.moveTo(oldx,oldy);
ctx.lineTo(newx,newy);
ctx.strokeStyle=lineColor;
ctx.lineWidth=linw;
ctx.lineCap="round";
ctx.stroke();
oldx=newx;
oldy=newy;
};
};
</script>
</body>
</html>