December 19, 2013

HTML5 Canvas: State Stacking

Stacking states with Canvas

Introduction

This is the first post of a series about HTML5 Canvas. In this article I will explain the meaning of context.save() and context.restore(). Simply said, these methods are reponsible for stacking the contexts states. But what does it mean?

What are states in Canvas?

First, it is necessary to know, what states are. The simplified answer is: Everything that does not draw!
The Canvas API provides a set of methods which can be distinguished between drawing methods and auxiliary methods. A good part (not all) of these auxiliary methods are used to define the appearance of drawn areas, and/or paths. For example, strokeStyle, fillStyle, globalAlpha, lineWidth, shadowOffsetX, shadowOffsetY, shadowBlur, shadowColor, font, textAlign, textBaseline etc. are all methods which modify states. Also considered as a state is the transformation matrix, which is modified by the methods translate, rotate, scale, setTransform. Another kind of state is a defined clipping region, modified by clip; Everything modified by these methods are states, which can be stacked.

What can I do with stacking?

Obviously, it is easy to recover already set states by simply popping it from the stack, because sometimes it is quite cumbersome to define a proper state. This also keeps your code cleaner. Stacking can even improve runtime performance, as demonstrated here at JsPerf. Another important advantages is the "isolatation" of state dependent operations. In the next paragraph I'll explain this concept more precisely.

Isolation of state dependent operations

Using state stacking you can isolate some and group other state operations quite easily. Imagine a car whose wheels shall rotate, while the car is moving forward. You can isolate the rotation of the wheels during their painting by stacking the "translation matrix" and apply the rotation. Afterwards, you restore the "translation matrix" and paint the next frame. The following snippet demonstrate this principle by transforming texts. Here is the visual result.
And here comes the code.
function main(){
    var context = document.getElementById('myCanvas').getContext('2d');
    
    var painter = new Painter(context);
    
    painter.setFillColor(255,0,0,1);
    painter.drawText("Text 1", 50);    
    painter.pushState();    
    painter.rotate(320, 100, 45);
    painter.setFillColor(0,0,255,1);
    painter.drawText("Text 2", 100); 
    painter.popState();
    painter.drawText("Text 3", 150);                
}
function Painter(ctx){
    var context = ctx;
    var DEG2RAD = Math.PI/180.0;
    var center = {};
        
    var init = function(ctx){
        context = ctx;
        center[0] = context.canvas.width/2;
        center[1] = context.canvas.height/2;
    };
            
    this.pushState = function(){
        context.save();
    };
    
    this.popState = function(){
        context.restore();
    };
    
    this.rotate = function(posX, posY, angle){
        context.translate(posX, posY);
        context.rotate(angle * DEG2RAD);
        context.translate(-posX, -posY);
    };
    
    this.setFillColor = function(r,g,b,a){
        context.fillStyle = "rgba(" + r + "," + g + "," + b + "," + a +")";
    };
    
    this.drawText = function(text, ypos){        
        context.save();
        context.font = "30px Arial";
        context.textAlign = "center";
        context.fillText(text, center[0], ypos);
        context.restore();              
    };
        
    init(ctx);
}

6 comments:

  1. The codes are really helpful for me to learn some tricks in these canvas method. Thank for the sharing.

    Advanced app development in coimbatore | Alternate mobile apps solutions

    ReplyDelete
  2. I am all that much satisfied with the substance you have said. I needed to thank you for this extraordinary article. To know more top hashtag on instagram, please go to site piknu

    ReplyDelete
  3. Emblix Academy – Digital marketing institute in KPHB, we address all major and minor aspects required for any student’s advancement in digital marketing. Clutch USA named our Digital Marketing Institute the best SEO firm.

    The future of digital marketing is promising and full of possibilities.

    As a result, skilled digital marketers who can keep up with the rising demand are in high order.
    In the Emblix Academy Digital marketing institute in KPHB, you will learn about all the major and minor modules of digital marketing, from Search engine marketing to Social Media Marketing and almost all Tools used for Digital Marketing.
    One stop place for all Digital Marketing courses! Emblix Academy is a Team of dedicated Professionals with 12years of experience in various Digital Platforms. We assure to provide the best Digital Marketing courses to enhance your Career.
    Certifications

    • Search Advertising
    • Display Advertising
    • Analytics Certification
    • Hubspot Certification
    • Bing Certification
    • Twitter Certification
    • Facebook Certification



    https://emblixacademy.com/

    ReplyDelete


  4. Comprehensive experience of association with 100+ corporates globally. Highly exclusive and bespoke training problems starting from the entry-level and varying to leadership levels. We are providing corporate digital marketing training in Hyderabad for the last many years and have created a significant presence as a corporate digital marketing training company.

    Our Way of Corporate Training

    Over the last few years, the evolution of the internet and its applications has reported an immense adaption amongst the people. The digital transformation has just created an upside change in the way the businesses used to operate earlier. It has fundamentally shifted the focus of companies towards new and improved ways of operating the business. In this new era of digitization, any business that denies going with this trend may get disrupted within the next few years. The corporate digital marketing training in Hyderabad has helped many companies and business ventures to upscale their business and help them achieve exponential growth. Our training model is strategically designed and developed to inhibit businesses get the most profound and right amount of knowledge that helps them to upscale their business. We intend to provide any business the source of training that helps them to make a profitable source of revenue with the help of our training.

    So let’s get a brief insight into our role and the strategies that we focus upon to upscale any business. We work on a 5 step methodology that is quite simple but extremely effective in creating a digital presence for the company.

    https://www.emblixsolutions.com/corporate-digital-marketing-training-in-hyderabad/

    ReplyDelete
  5. This comment has been removed by the author.

    ReplyDelete
  6. The public authority is on target to utilizing the IT capability of the country. As of late, South African pioneers declared an objective to prepare north of 1 million experts in Mechanical technology, man-made intelligence, Distributed computing, and Programming.

    To recruit a far off programming designer, South Africa is a sound decision since the IT market is quickly creating, it hasn't completely developed at this point. Information assurance and security are a portion of the significant trouble spots of the nearby tech local area. As indicated by a PwC report, 32% of nearby IT firms conceded to being network protection assault casualties - just a third out of these groups had a reaction plan>> Mobilunity

    ReplyDelete