1

I'm adding image to canvas and then trying to add text on the top of the image. Text is binded to text input. The problem is that when I type text in the field, instead of redrawing, it's duplicate itself.

My directive:

.directive('memeimage', function () {
      return {
        restrict: 'A',
        link: function (scope, el, attrs) {

          scope.upperText = "";
          scope.fontsize = 50;

          scope.drawCanvas = function () {

            var canvas = el[0];
            var context = canvas.getContext("2d");

            context.font = scope.fontsize + "px  Impact";
            context.fillStyle = 'white';
            context.strokeStyle = 'black';
            var x = canvas.width / 2;
            var y = canvas.height / 6;
            context.textAlign = 'center';
            context.fillText(scope.upperText.toUpperCase(), x, y);
            context.lineWidth = 2;
            context.strokeText(scope.upperText.toUpperCase(), x, y);


          };
        }
      }
    });

Here's fiddle: http://jsfiddle.net/HB7LU/5085/

How to avoid this and to not duplicate text? Clearing canvas isn't way to go, because I'have also using image on same canvas.

Thanks

Fyodor Khruschov
  • 1,657
  • 7
  • 23
  • 40

3 Answers3

0

The easy answer is that you use multiple overlapping canvas elements. That will give you the freedom to clear the text and still keep the image(s) underneath.

When you're ready to export to an image, you can use the solution found below to draw your multiple canvases to a single image:

Save many canvas element as image

Community
  • 1
  • 1
Justin Niessner
  • 242,243
  • 40
  • 408
  • 536
  • I'm interesting, how guys can do this without multiple canvases? http://mobiforge.com/design-development/html5-canvas-meme-generator – Fyodor Khruschov Jul 22 '14 at 00:13
  • @n8m - Their code is simple. They clear the canvas every time the text changes. They then transform and redraw the image along with the text. All of their source is visible in a debugger. – Justin Niessner Jul 22 '14 at 14:33
0

Why not use SVG instead of Canvas? You'll have better control of individual elements especially since you're trying to bind to an input control.

rchawdry
  • 1,256
  • 1
  • 10
  • 14
0

You have to redraw the canvas with clearRect or change the canvas width or height.

Fiddle

c.width = c.width
Dylan
  • 4,703
  • 1
  • 20
  • 23
  • this will delete another stuff on the canvas including the image which I mentioned – Fyodor Khruschov Jul 21 '14 at 23:36
  • Well you either 1) Redraw the whole canvas every update including your images 2) Maintain multiple layered canvas' 3) switch to svg where you can manage individual elements. – Dylan Jul 22 '14 at 03:06