Wednesday, September 5, 2012

Draw Something JS - Part #2

In my previous post, I talked about how to draw lines with different widths and colors on HTML5 canvas elements, very easy!
In this post, We will discuss about how to record the user movements and "play" it on the canvas.
The main idea is to save each mouse position to an array, loop over the array and paint on the canvas element.
The Array definition in Javascript: 
var recordDataArray = []; // best practice to use [] instead of new Array();
On each mousedown/mousemove event we need to push to the array the following data:
  • mouse x position
  • mouse y position
  • event type (mousedown to begin a new line path or mousemove to continue the line path on the canvas)
  • line color
  • line width
Define the event type enum in Javascript:
var DrawEventType = {
    START: 0,
    MOVE: 1
}
Now, We will modify our functions from the previous post to push the data to the array:
 var startPaintWithMouse = function(event) {
            mouseState = 1;
            brushCtx = board.getContext('2d');
            brushCtx.beginPath();
            brushCtx.lineWidth = lineWidth;
            brushCtx.strokeStyle = color;
            brushCtx.moveTo(event.offsetX,event.offsetY);
            // push to array
            recordDataArray.push({
                  type: DrawEventType.START,
                  x:event.offsetX,
                  y:event.offsetY,
                  color:color,
                 width:lineWidth
             });
};
var movePaintWithMouse = function(event) {
             if (mouseState == 1) {
                   event.preventDefault();
                   brushCtx = board.getContext('2d');
                   brushCtx.lineTo(event.offsetX,event.offsetY);
                   brushCtx.stroke();
                   recordDataArray.push({                            type:DrawEventType.MOVE,
                            x:event.offsetX,
                            y:event.offsetY,
                            color:color,
                            width:lineWidth
                   });
            }
};
We can create a button that clear the canvas.
Clearing the canvas in Javascript is easy too:
var brushCtx = board.getContext('2d');
brushCtx.clearRect(0, 0, board.width, board.height);
And now, we can create a play button that loop over the array and paint the user movements on the canvas.
We need to use the setInterval javascript method to give the user the drawing experience.
var playDataArray = function(dataArray,speed) {
            var dataIndex = 0;
            var playInterval = setInterval(function(){
                   if (typeof(dataArray[dataIndex]) == 'object') {
                            drawDataObject(dataArray[dataIndex]);
                            dataIndex++;
                   } else {
                            clearInterval(playInterval);
                   }
            },speed);
};
On each interval iteration we call the drawDataObject method which gets an object from our array and draw it.
var drawDataObject = function(data) {
            if (data.type == DrawEventType.START) {
                       brushCtx = board.getContext('2d');
                       brushCtx.beginPath();
                       brushCtx.lineWidth = data.width;
                       brushCtx.strokeStyle = data.color;
                       brushCtx.moveTo(data.x,data.y);
            } else if (data.type == DrawEventType.MOVE) {
                       brushCtx = board.getContext('2d');
                       brushCtx.lineTo(data.x,data.y);
                       brushCtx.stroke();
            }
};
That's all!

18 comments:

  1. I'll try to make it this way. Thank you for your tips. I hope that they will be useful for me.

    ReplyDelete
  2. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Front end developer learn from Javascript Training in Chennai . or learn thru JavaScript Online Training India. Nowadays JavaScript has tons of job opportunities on various vertical industry. JavaScript Training in Chennai

    ReplyDelete
  3. Thank you for sharing this post.Really very informative post you shared here. Kindly keep blogging.
    Best Software testing Training in Bangalore
    Best web Designing Training in Bangalore

    ReplyDelete
  4. I suppose that we need to use this method to give the user the best drawing experience possible.

    ReplyDelete
  5. If you wish for to improve your know-how only keep visiting this site and be updated with the most up-to-date news update posted here. yahoo email login

    ReplyDelete
  6. The article is very exciting to read. By the way, your dog is truly a best friend. Happy many returns of the day! pikview

    ReplyDelete
  7. This is the motivation behind why it is the most well known application store for Android. On the off chance that you will ApkMarkt
    the application, it would be an extraordinary plan to chec

    ReplyDelete
  8. It's Really A Great Post. Looking For Some More Stuff.



    shriram break free

    ReplyDelete
  9. Great survey, I'm sure you're getting a great response.

    ReplyDelete
  10. Kami juga menyediakan pengeluaran togel taiwan setiap harinya, untuk mempermudah prediksi prediksi kita kedepannya, karena master prediksi yang berkerja sama dengan kami pun menggabungkan beberapa metode prediksi, dan data pengeluaran merupakan salah satu metode yang cukup ampuh. Prediksi Taiwan

    ReplyDelete
  11. The amount of money given per wager is often very small and often varies with game choice. A casino might offer three comp factors 카지노 사이트 for each $10 wagered on slots and one comp point for each $10 wagered on blackjack. This instance is equal to returning 0.3% of wagers on slots and 0.1% of wagers on blackjack.

    ReplyDelete
  12. Heralddiary sites foster a sense of community among their readers. Users can engage with content creators and fellow readers through comment sections, social media integration, and discussion forums. This sense of belonging and interaction further fosters the user experience, turning passive readers into active participants in the site's community. theheralddiary

    ReplyDelete