February 23, 2015

Make a Backbone.js to draw objects on a canvas

Make a Backbone.js to draw objects on a canvas

This is my first Backbone.js app. Here I tried drawing a rectangle into the canvas using the Backbone View. And I added a small functionality like move on click. The rectangle keeps on moving and changing its position on clicking it.

HTML

<div id="canvas">Click on the rectangle...</div>

CSS

.rectangle {
   position: absolute;
   border: 4px solid #fff;
   cursor: pointer;
}
#canvas {
   color: #fff;
   font-family: "Arial", san-serif;
   margin: 20px;
}

The main part comes here - the backbone.js coding

JavaScript

(function () {

 var Rectangle = Backbone.Model.extend({ });
 var RectangleView = Backbone.View.extend({

  tagName: 'div',

  className: 'rectangle',

  events: {
   'click': 'move'
  },

  render: function () {
   this.setDimensions();
   this.setPosition();
   this.setColor(); 
   return this;
  },

  setDimensions: function () {
   var width = this.model.get('width') + 'px';
   var height = this.model.get('height') + 'px';
   this.$el.css({
    width: width,
    height: height
   })
  },

  setPosition: function () {
   var position = this.model.get('position');
   this.$el.css({
    left: position.x,
    top: position.y
   });
  },

  setColor: function () {
   this.$el.css('background-color', this.model.get('color')) 
  },

  move: function () {
   this.$el.css('left', this.$el.position().left + 10)
  }

 });

 var myRectangle = new Rectangle({
  width: 100,
  height: 60,
  position: {
   x: 300,
   y: 150
  },
  color: '#ff0000'
 });

 var myView = new RectangleView({model: myRectangle});
 $('div#canvas').append(myView.render().el);

})();

Attachments:

I have used external attachments.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.7.0/underscore-min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.2/backbone-min.js"></script>
demo

No comments:

Post a Comment

Popular Posts

Views