Javascript examples for Canvas:Draw
Draw a square in javascript using canvas
<html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <script type="text/javascript" src="https://code.jquery.com/jquery-1.9.1.js"></script> <style id="compiled-css" type="text/css"> body {//ww w. jav a 2 s . co m background-color: ivory; padding:20px; } #canvas { border:1px solid red; } input { width:15px; } </style> <script type="text/javascript"> $(window).load(function(){ var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); var canvasOffset = $("#canvas").offset(); var offsetX = canvasOffset.left; var offsetY = canvasOffset.top; var startX; var startY; var isDown = false; ctx.fillStyle = "skyblue"; ctx.strokeStyle = "lightgray"; ctx.lineWidth = 3; var modeName = "square"; $('input[name=mode]').click(function () { modeName = $('input[name=mode]:checked').val(); console.log(modeName); }); function handleMouseDown(e) { mouseX = parseInt(e.clientX - offsetX); mouseY = parseInt(e.clientY - offsetY); // Put your mousedown stuff here startX = mouseX; startY = mouseY; isDown = true; } function handleMouseUp(e) { mouseX = parseInt(e.clientX - offsetX); mouseY = parseInt(e.clientY - offsetY); $("#uplog").html("Up: " + mouseX + " / " + mouseY); isDown = false; } function handleMouseMove(e) { mouseX = parseInt(e.clientX - offsetX); mouseY = parseInt(e.clientY - offsetY); if (!isDown) { return; } ctx.clearRect(0, 0, canvas.width, canvas.height); switch (modeName) { case "rectangle": drawRectangle(mouseX, mouseY); break; case "square": drawSquare(mouseX, mouseY); break; default: break; } } function drawRectangle(mouseX, mouseY) { var width = mouseX - startX; var height = mouseY - startY; ctx.beginPath(); ctx.rect(startX, startY, width, height); ctx.fill(); ctx.stroke(); } function drawSquare(mouseX, mouseY) { var width = Math.abs(mouseX - startX) * (mouseX < startX ? -1 : 1); var height = Math.abs(width) * (mouseY < startY ? -1 : 1); ctx.beginPath(); ctx.rect(startX, startY, width, height); ctx.fill(); ctx.stroke(); } $("#canvas").mousedown(function (e) { handleMouseDown(e); }); $("#canvas").mousemove(function (e) { handleMouseMove(e); }); $("#canvas").mouseup(function (e) { handleMouseUp(e); }); }); </script> </head> <body> <canvas id="canvas" width="300" height="300"></canvas> <br> <input type="radio" id="rect" name="mode" value="rectangle"> <label for="rect">Rectangle</label> <input type="radio" id="sqr" name="mode" value="square" checked> <label for="sqr">Square</label> </body> </html>