d2jsp
Log InRegister
d2jsp Forums > Off-Topic > Computers & IT > Programming & Development > Playing With Canvas & Javascript > W/ Source
Add Reply New Topic New Poll
Member
Posts: 7,094
Joined: Dec 24 2006
Gold: 1,100.00
Aug 7 2013 01:44pm
I was bored so I made a drawing canvas, a random shape/color generator, and a pretty little scene with a ninja running across it.
http://d1jsp.org/ffspk/canvas.html


source:
Quote


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

<title>Canvas - Andrew Allen</title>

<style type="text/css">

  #page{

    width:960px;

    margin:auto;

    background-color:#888;

    border:3px solid #444;

    min-height:900px;

  }

  #scribbler{

    margin:5px 5px 5px 80px;

    border:3px solid #444;

    width:400px;

    background-color:#FFF;

    float:left;

    min-height:400px;

  }

  #randomShapes{

    margin:5px 5px 5px 5px;

    border:3px solid #444;

    width:400px;

    float:left;

    min-height:400px;

    background-color:#FFF;

  }

  #canvas{ /* primitive landscape */

    margin:5px 5px 5px 80px;

    border:3px solid #444;

    background-color:#FFF;

    width:800px;

    min-height:400px;

  }

  /*CSS For Buttons*/

  #scribbler-buttons{

    width:400px;

    margin:0px 0px 0px 100px;

  }

  .scribbler-button{

    margin:0px 20px 0px 0px;

    float:left;

    background-color:#444;

  }

  #randomShapes-buttons{

    width:400px;

    margin:0px 0px 0px 50px;

    float:left;

  }

  #colorButton{

    float:right;

    color:#000000;

  }

  #thinnerButton{

    margin:auto;

  }

  .randomShapes-button{

    float:left;

    margin:0px 20px 0px 0px;

    background-color:#444;

  }

</style>

<script type="text/javascript" src="Animation Files/GameObject.js"></script>

<script type="text/javascript" src="Animation Files/VisualGameObject.js"></script>

<script type="text/javascript" src="Animation Files/RepeatingGameObject.js"></script>

  <script type="text/javascript" src="Animation Files/AnimatedGameObject.js"></script>

  <script type="text/javascript" src="Animation Files/Utils.js"></script>

  <script type="text/javascript" src="Animation Files/ApplicationManager.js"></script>

  <script type="text/javascript" src="Animation Files/GameObjectManager.js"></script>

<script type="text/javascript">

  var draw; // The scribbler context for the scribbler canvas.

  var shapes; //The random shapes context for the randomShapes canvas

  var scribbler; //Contains a reference to the scribbler canvas element

  var scene; //The 2d context reference to the scene canvas element

  var sceneCanvas; //reference to canvas context

  var allowDraw = false; //Used to only allow user to draw when mouse is down

  var lineWidthVar; //Self explanatory

  var strokeStyleVar; //Holds color in hex

  var x,y; //Location coordinates to draw something

  //The following variables are used for our ninja object that will run across our primitive landscape

  var FPS = 30;

  var SECONDS_BETWEEN_FRAMES = 1 / FPS;

  var g_GameObjectManager = null;

  var g_run = new Image();

  g_run.src = "Animation Files/run.png";

 

  //Our function to access elements in the DOM with less typing ;)

  var $ = function(id){ return document.getElementById(id); }

 

  function init(){

  start_scribbler();

  start_randomShapes();

  start_scene();

  new GameObjectManager().startupGameObjectManager(); //our ninja

  }

 

  /* Initialize the canvas for drawing. */

  function start_scribbler ()

  {

      scribbler = $("scribbler");

      draw = scribbler.getContext ("2d"); 

    lineWidthVar = 4.0;   

      draw.lineWidth = lineWidthVar; // line width

    strokeStyleVar = "#000000";

      draw.strokeStyle = strokeStyleVar; //line color   



      // set up event handlers - anonymous functions

      scribbler.onmousedown = function(event) { mousedown(event) };

      scribbler.onmouseup  = function(event) { mouseup(event)  };   

      scribbler.onmousemove = function(event) { mousemove(event) };

    scribbler.onmouseout = function(event)  { mouseout(event)  }; //Mouse has left canvas

  }

 

  function start_randomShapes()

  {

  var rndShapes = $("randomShapes");

  shapes = rndShapes.getContext("2d");

  }

 

  /* Function to increase line width on our scribbler */

  function thicker(){

  lineWidthVar += 1;

  draw.lineWidth = lineWidthVar;

  }

 

  /* Function to decrease line width on our scribbler */

  function thinner(){

  lineWidthVar -= 1;

  draw.lineWidth = lineWidthVar;

  }

 

  //Change the color of our scribbler line to a different color each time the color button is clicked

  function changeColor(){

  if(strokeStyleVar == "#000000"){

  strokeStyleVar = "#FF0000";

  draw.strokeStyle = strokeStyleVar;

  document.getElementById("colorButton").style.color = strokeStyleVar;

  }else if(strokeStyleVar == "#FF0000"){

  strokeStyleVar = "#00FF00";

  draw.strokeStyle = strokeStyleVar;

  document.getElementById("colorButton").style.color = strokeStyleVar; 

  }else if(strokeStyleVar == "#00FF00"){

  strokeStyleVar = "#0000FF";

  draw.strokeStyle = strokeStyleVar;

  document.getElementById("colorButton").style.color = strokeStyleVar;

  }else if(strokeStyleVar == "#0000FF"){

  strokeStyleVar = "#FFE600";

  draw.strokeStyle = strokeStyleVar;

  document.getElementById("colorButton").style.color = strokeStyleVar;

  }else if (strokeStyleVar == "#FFE600"){

  strokeStyleVar = "#8E6B23";

  draw.strokeStyle = strokeStyleVar;

  document.getElementById("colorButton").style.color = strokeStyleVar;

  }else{

  strokeStyleVar = "#000000";

  draw.strokeStyle = strokeStyleVar;

  document.getElementById("colorButton").style.color = strokeStyleVar;

  }

  } //End changeColor()



  /* Function to clear scribbler canvas*/

  function clearScribbler(){

  draw.clearRect(0,0,400,400);

  }



  /* function to get our mouse coordinates, accounting for offsets and different browsers */

  function getXY(event)

  {

  //Firefox

  if (event.pageX || event.pageY){

    x = event.pageX;

    y = event.pageY;

  } else{ //Opera

    x = event.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;

    y = event.clientY + document.body.scrollTop + document.documentElement.scrollTop;

  }

  x -= scribbler.offsetLeft;

  y -= scribbler.offsetTop;



  }

 

  /* When user presses mouse button down, allow them to draw */

  function mousedown(event) {

  getXY(event);

  allowDraw = true;

  draw.beginPath();

  draw.moveTo(x, y);

  }



  /* When user lets go of mouse button, disallow them to draw */

  function mouseup(event){

  if(allowDraw){

  allowDraw = false;

  mousemove(event);

  }

  }

 

  /* React to a mouse move. */

  function mousemove(event){

    if(allowDraw){ 

    getXY(event);

    draw.lineTo(x, y);

    draw.stroke();

    }

  }

 

  /* If mouse is out of canvas, set allowdraw to false so that when they bring mouse back in it wont continue to draw despite

  mouse button not being pressed down */

  function mouseout(event){

  allowDraw = false;

  }

 

  /* Function to draw our random circles in a pattern (paradox?) */

  function toggleCircles(){ 

  /* Get our random location */

  var centerX = parseInt(Math.floor(Math.random()*390+10));

    var centerY = parseInt(Math.floor(Math.random()*390+10)); 

 

  /* Get our random size */

  radius = parseInt(Math.floor(Math.random()*100+10));

 

  //We want to keep the full circle within the canvas

  var test;

  test = centerX + radius;

  if(test > 400){

  centerX -= radius;

  }

  test = centerY + radius;

  if (test > 400){

  centerY -= radius;

  }

 

 

  /* Draw our random circles */

  var i = parseInt(0);

  for(i=0; i<5; i++){

  shapes.beginPath();

  //Quote  Wyatt: "draw 5 graphical circles (arcs) of random size, shape and color" (http://www.jbwyatt.com/270/a/a5Canvas.htm)

  //How can circles be different random shapes? If they were a different shape they wouldnt be circles. Making random arc function incase.

  shapes.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);

  shapes.fillStyle = "rgba("+parseInt(Math.floor(Math.random()*255))+", "+parseInt(Math.floor(Math.random()*255))+", "+parseInt(Math.floor(Math.random()*255))+",1)";

  shapes.fill();

  radius -= parseInt(Math.floor(Math.random()*(radius/(i+1))));

  shapes.closePath();

  }

  }

 

  /* Essentially the same function as random circles, but with a random start angle to give different shapes */

  function toggleArcs()

  {

  /* Get our random location */

  var centerX = parseInt(Math.floor(Math.random()*390+10));

    var centerY = parseInt(Math.floor(Math.random()*390+10)); 

 

  /* Get our random size */

  radius = parseInt(Math.floor(Math.random()*100+10));

 

  //We want to keep the full circle within the canvas

  var test;

  test = centerX + radius;

  if(test > 400){

  centerX -= radius*2;

  }

  test = centerY + radius;

  if (test > 400){

  centerY -= radius*2;

  }

 

 

  /* Draw our random arcs - added this one to compensate for if I wasn't satisfying the "random shapes" criteria for the random circles */

  var i = parseInt(0);

  for(i=0; i<5; i++){

  shapes.beginPath();

  shapes.arc(centerX, centerY, radius, Math.random()*((radius/2)/(i+1)), 2 * Math.PI, false);

  shapes.fillStyle = "rgba("+parseInt(Math.floor(Math.random()*255))+", "+parseInt(Math.floor(Math.random()*255))+", "+parseInt(Math.floor(Math.random()*255))+",1)";

  shapes.fill();

  radius -= parseInt(Math.floor(Math.random()*(radius/(i+1))));

  shapes.closePath();

  } 

  }

 

  function toggleRectangles(){

  /* Fariables for our random coordinates used in determining the size of the rectangles */

  var randomSizeX;

  var randomSizeY;

 

  /* Variables for our random location */

  var locX;

  var locY;

  var acceptable = false;

 

  //Get our begin and end coordinates until it generates an acceptable rectangle

  while(!acceptable){

  randomSizeX = parseInt(Math.floor(Math.random()*100+100));

  randomSizeY = parseInt(Math.floor(Math.random()*100+100));

  locX = parseInt(Math.floor(Math.random()*400));

  locY = parseInt(Math.floor(Math.random()*400));

  if(locX + randomSizeX > 400){ //Rectangle is going past right edge

    locX -= ((randomSizeX + locX)-400); //Subtract from locX the amount of rectangle going off edge

  }

  if(locY + randomSizeY > 400){ //Rectangle is going past bottom edge

    locY -= ((randomSizeY + locY)-400); //Subtract from locY the amount of rectangle going off edge

  }

  if((locX < randomSizeX) && (locY < randomSizeY)){  //Make sure begin coordinates arn't past end coordinates

    acceptable = true;

  }

  }

 

  /*Save a copy of randomSizeX and randomSizeY, since we will manipulate these*/

  var prevSizeX = randomSizeX;

  var prevSizeY = randomSizeY;

 

  //Use variable to limit the randomness so we dont get too tiny of rectangles that would prevent more random rectangles

  //from being put within

  var limitX = randomSizeX / 5;

  var limitY = randomSizeY / 5;

 

  /* Backup initial location, we use these in formatting our internal rectangles */

  var prevLocX = locX;

  var prevLocY = locY;

 

  var j = parseInt(0);

  for(j=0; j<5; j++){

  shapes.beginPath();

  shapes.fillRect(locX, locY, randomSizeX, randomSizeY);

  shapes.fillStyle = "rgba("+parseInt(Math.floor(Math.random()*255))+", "+parseInt(Math.floor(Math.random()*255))+", "+parseInt(Math.floor(Math.random()*255))+",1)";

  shapes.fill();

  shapes.closePath();

 

  /* Calculate location and size of next square */ 

  randomSizeX -= parseInt(Math.floor(Math.random()*prevSizeX));

  randomSizeY -= parseInt(Math.floor(Math.random()*prevSizeY));   

  locX += parseInt(Math.floor(Math.random()*limitX+3)); //Must fall within the area of previous rectangle

  if(locX > prevSizeX)

    locX -= (locX - prevLocX);

  locY += parseInt(Math.floor(Math.random()*limitY+3)); //Must fall within the area of previous rectangle

  if(locY > prevSizeY)

    locY -= (locY - prevLocY);

  while((locX + randomSizeX) > (prevSizeX + prevLocX)){ randomSizeX--; }

  while((locY + randomSizeY) > (prevSizeY + prevLocY)){ randomSizeY--; }





  prevLocX = locX;

  prevLocY = locY; 

  prevSizeX = randomSizeX;

  prevSizeY = randomSizeY;

  }

  }

 

  /* Function to clear Random Shapes/Rectangles canvas */

  function toggleClear(){

  shapes.clearRect(0,0,400,400);

  }

 

  function start_scene(){

  sceneCanvas = $("canvas");

  scene = sceneCanvas.getContext ("2d");

  drawSky();

  drawGrass(); 

  drawHouse();

  drawTree(700,200);

  drawSun();

  drawPerson(500,220);

  }

 

  function drawGrass(){

  var x1 = 0;

  var y1 = 390;

  var x2 = 800;

  var y2 = 10;

  var amountOfGreen = parseInt(80);

  for(i = 0; i < 20; i++) //Twenty increasingly lighter-green rectangles from bottom to top (trying for depth perception here with the sun...)

  { 

    scene.fillStyle = "rgba(0," + amountOfGreen + ",0,1)";

    scene.fillRect(x1,y1,x2,y2);

    y1 -= 10;

    amountOfGreen += 5;

  }

  }

 

  function drawSky(){

  /* Draw Sky */

  var x1 = 0;

  var y1 = 195;

  var x2 = 800; 

  var y2 = 10;

  var amountOfBlue = parseInt(200);

  for(i = 0; i < 40; i++)

  {

    scene.fillStyle = "rgba(0,0,"+ amountOfBlue +",1)";

    scene.fillRect(x1,y1,x2,y2);

    y1 -= 5;

    amountOfBlue -= 5;

  }   

  }

 

  function drawHouse(){

  //Main part

    scene.fillStyle = "rgb(100,0,0)";

    scene.fillRect(100,100,140,140);   

  //Draw roof

    // Set the style properties.

    scene.fillStyle  = '#8B6969';

    scene.strokeStyle = '#8B6969';

    scene.lineWidth  = 4;

    scene.beginPath();   

    scene.moveTo(80, 100);// Start from the left most point, and work our way clockwise

    scene.lineTo(160, 80);

    scene.lineTo(250, 100);

    scene.lineTo(80, 100);

    scene.fill();

    scene.stroke();

    scene.closePath();

  //Draw door

    scene.fillStyle = '#5E2612';

    scene.fillRect(120,180,30,60);

  //Draw windows

    scene.fillStyle = '#292421';

    scene.fillRect(120,130,30,30); //Top left

    scene.fillRect(180,130,30,30); //Top Right

    scene.fillRect(160,185,50,30);

  }

 

  function drawTree(x, y){

  scene.fillStyle = '#5E2605';

  scene.fillRect(x, y, 30, 100);

  scene.save();

  scene.rotate(0.23);

  scene.fillRect(x+65, y-180,10,88); //right branch

  scene.restore();

  //leaves

  scene.fillStyle = '#006600';

  scene.beginPath();

  scene.arc(x,y-20,30,0,2 * Math.PI, true);

  scene.arc(x+25,y-20,30,0,2 * Math.PI, true);

  scene.arc(x+45,y-20,30,0,2 * Math.PI, true);

  scene.arc(x+30,y-40,30,0,2 * Math.PI, true);

  scene.fill();

  scene.closePath();

  }

  function drawSun(){

  scene.fillStyle = '#FFFF00';

  scene.beginPath();

  scene.arc(400,200,30,0,Math.PI, true);

  scene.fill();

  scene.closePath();

  }

  function drawPerson(x,y){

  //Head

  scene.fillStyle = '#000000';

  scene.beginPath();

  scene.arc(x,y,10,0,2*Math.PI, true);

  scene.fill();

  scene.closePath();

  //Body

  scene.beginPath(); 

  scene.strokeStyle = '#000000';

  scene.moveTo(x,y);

  scene.lineTo(x,y+50);

  scene.stroke();

  //Arms

  scene.beginPath(); 

  scene.moveTo(x,y+15); //Left arm

  scene.lineTo(x-30,y);

  scene.moveTo(x, y+15);

  scene.lineTo(x+30, y); //Right arm

  scene.stroke();

  //Legs

  scene.beginPath();

  scene.moveTo(x, y+50);

  scene.lineTo(x-15, y+80);

  scene.moveTo(x, y+50);

  scene.lineTo(x+15, y+80);

  scene.stroke();

  }

</script>

</head>

<body onload="init()">

<div id="page">

  <!--Sketch Canvas-->

  <canvas id="scribbler" width="400" height="400"></canvas>

 

  <!--Random Shapes Canvas-->

  <canvas id="randomShapes" width="400" height="400"></canvas>

 

  <!--Our buttons below our two side-by-side canvas elements -->

  <div id="scribbler-buttons">

  <div class="scribbler-button"><button type="button" onclick="thicker()">+Line Width</button> </div>

  <div class="scribbler-button"><button type="button" id ="thinnerButton" onclick="thinner()">-Line Width</button> </div>

  <div class="scribbler-button"><button type="button" onclick="clearScribbler()">Clear</button> </div>

  <div class="scribbler-button"><button type="button" id="colorButton" onclick="changeColor()">Color</button></div>

  </div> 

  <div id="randomShapes-buttons">

  <div class="randomShapes-button"><button type="button" onclick="toggleCircles()">Circles?</button> </div>

  <div class="randomShapes-button"><button type="button" onclick="toggleArcs()">Arcs?</button> </div>

  <div class="randomShapes-button"><button type="button" onclick="toggleRectangles()">Rectangles?</button> </div>

  <!--<div class="randomShapes-button"><button type="button" onclick="toggleRandomness()">Randomness?</button> </div> -->

  <div class="randomShapes-button"><button type="button" onclick="toggleClear()">Clear</button> </div>

  </div>

 

  <!--Primitive Landscape Canvas-->

  <canvas id="canvas" width="800" height="400"></canvas>

</div>
</body>

</html>
Member
Posts: 827
Joined: Jan 16 2012
Gold: 0.00
Warn: 10%
Aug 7 2013 03:45pm
grats
Member
Posts: 32,925
Joined: Jul 23 2006
Gold: 3,804.50
Aug 7 2013 05:07pm
use fiddle next time instead of posting a lot of source.

http://jsfiddle.net/
Go Back To Programming & Development Topic List
Add Reply New Topic New Poll