Dipto Roy
Dipto Roy

Reputation: 163

Draw a rectangle over a background image in HTML5 Canvas on Angular.js

I want to draw a rectangle over a background image on canvas using angular.js. I can draw it by placing the rectangle code inside the image.onload function.But I want them to be separated.How can I do it?

$scope.printStars = function() {
                var c = document.getElementById("myCanvas");
                c.width=1920;
                c.height=1080;

                var ctx = c.getContext("2d");
                ctx.clearRect(0, 0, 800, 800);


                ctx.scale(c.width/1920,c.height/1080);
                ctx.translate(1920-500,0);
                 var imagePaper = new Image();


               imagePaper.onload = function(){


                    ctx.drawImage(imagePaper,100, 20, 500,500);



                };
                ctx.fillRect(20, 20, 200, 200);

                imagePaper.src = "Img/Back1.jpg";





            }

My code works if I do this

 imagePaper.onload = function(){


                    ctx.drawImage(imagePaper,100, 20, 500,500);
                    ctx.fillRect(20, 20, 200, 200);


                };

But I want the drawrectangle code outside of image function.

Upvotes: 0

Views: 723

Answers (1)

Ruben Helsloot
Ruben Helsloot

Reputation: 13129

You can assign the ctx to a variable on the $scope and access it in other places now. For example:

$scope.drawRectangle = function() {
  $scope.ctx.fillRect(20, 20, 200, 200);
}
<button ng-click=drawRectangle()>Draw rectangle</button>

Upvotes: 1

Related Questions