Canvas drawing with keyboard - Javascript Canvas

Javascript examples for Canvas:Key

Description

Canvas drawing with keyboard

Demo Code

ResultView the demo in separate window

<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. j  ava 2  s. c  o  m*/
   background-color: ivory;
}
canvas {
   border:1px solid red;
}


      </style> 
      <script type="text/javascript">
    $(window).load(function(){
var width = 10;
$(document).keydown(function (key) {
    if (key.which === 68) adjustWidth(1);
    else if (key.which === 65) adjustWidth(2);
});
var canvas = $("#canvas")[0];
var ctx = canvas.getContext("2d");
var w = $("#canvas").width();
var h = $("canvas").height();
ctx.fillStyle = "#C1DAD6";
ctx.fillRect(0, 0, w, h);
ctx.strokeStyle = "black";
ctx.strokeRect(0, 0, w, h);
function adjustWidth(iw) {
    ctx.clearRect(0, 0, w, h);
    ctx.fillStyle = "#C1DAD6";
    ctx.fillRect(0, 0, w, h);
    ctx.fillStyle = "grey";
    if (iw === 1) {
        width += 10;
        ctx.fillRect(0, 100, width + 10, 5)
    } else if (iw === 2) {
        width -= 10;
        if (width > 0) {
            ctx.fillRect(0, 100, width + 10, 5)
        }
    }
}
    });

      </script> 
   </head> 
   <body> 
      <p>Click on the canvas to get its focus</p> 
      <p>Then press the "D" key to lengthen the line</p> 
      <p>And press the "A" key to shorten the line</p> 
      <canvas id="canvas" width="300" height="300"></canvas>  
   </body>
</html>

Related Tutorials