Domanda

I need resize and redraw canvas, on mouse drawing.
I did demo, but this is not works, all time when i resize canvas it is clean all data

I tried different options like:

  • temporary canvas
  • toDataURL

But without success

È stato utile?

Soluzione

Your fiddle is working, i thing the only thing you missed is that resizing a canvas does clear it, so in the provided fiddle you clear it in fact on every single move of your mouse.

Edit : OK i think i understood your issues.

1) On resizing, you loose the content.
2) On resizing you loose current path, so you have to re-initiate a path drawing.
3) If you create a canvas on each mouse move, memory consumption will reach mountains and your app won't be reactive.
4) since the re-draw happens on a mouse move and not on a requestAnimationFrame, the whole thing will look quite hugly if you just do the full redraw on mouse move.

So i updated this fiddle so that it fixes all those issues :

try it here : http://jsfiddle.net/gamealchemist/JHr2P/78/

  • i handle a temp canvas that will double it size when not big enough (so it changes much less often size. use a factor less than 2X, or another caching strategy if you think appropriate). So the memory use will not be that big.
  • i save the image to temp canvas after stroking the line.
  • ( the image is store to localContent only on mouse up to reduce overhead ).
  • then i resize + redraw from the temp canvas.
  • then i re-initiate a line draw.
  • all of the above is done within a requestAnimationFrame to avoid hugly flickering.

store / restore code :

var _storeCanvas =  document.createElement('canvas');
var _storeCtx = _storeCanvas.getContext('2d');

function storeInTempCanvas() {
   if (_storeCanvas == null || _storeCanvas.width < canvas.width || _storeCanvas.height )    {   
    _storeCanvas.width = 2 * canvas.width; 
    _storeCanvas.height = 2 * canvas.height;
   }
   _storeCtx.drawImage(canvas, 0, 0);
}

function restorefromTempCanvas() {
    ctx.drawImage(_storeCanvas, 0, 0);
}

updated mouse move code :

var draw = {
      // ... same mousedwon code...

    mousemove: function(coordinates) {
        if (this.isDrawing) {
            requestAnimationFrame ( function() {
                        ctx.lineTo(coordinates.x, coordinates.y);
                        ctx.stroke();            
                        storeInTempCanvas();
                        canvas.width+=1;
                        restorefromTempCanvas();
                        ctx.beginPath();
                        ctx.moveTo(coordinates.x, coordinates.y);
            } );
       }
    },

 //... same mouseup code.


}  
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top