GetSubRaster and show in another canvas PaperJS

361 views Asked by At

I am new to JavaScript and PaperJS. What I am trying to do is:

1) Load image to canvas using raster - done

   var imageCanvas = document.getElementById('image-canvas');
   var drawCanvas = document.getElementById('draw-canvas');
   var img = document.getElementById('img');

  imageCanvas.width = img.width;
  imageCanvas.height = img.height;
  var scope = new paper.PaperScope();

  scope.setup(drawCanvas);
  scope.setup(imageCanvas);//this will be active

  var views = [2];
  views[0] = scope.View._viewsById['image-canvas'];
  views[1] = scope.View._viewsById['draw-canvas'];
  views[0]._project.activate(); //making sure we are working on the right canvas
  raster = new paper.Raster({source:img.src, position: views[0].center});

2) get the sub raster of the image; the rectangle is drawn by the user using mouse drag events. But for the sake of convenience lets say I have a rectangle at position (10,10) and dimensions (100,100) 3) get the sub raster and show the preview in other drawcanvas

views[1]._project.activate();// activating draw-canvas
var subras = raster.getSubRaster(new paper.Path.Rectangle(new paper.Point(10,10), new paper.Size(100,100))); //Ignore if the rectangle inside is not initialized correctly

But, nothing happens on the draw-canvas.

I also tried using

var subrasdata = raster.getSubRaster(new paper.Path.Rectangle(new paper.Point(10,10), new paper.Size(100,100))).toDataURL();

but it gives me

Uncaught SecurityError: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.

Is there any other way to get the sub raster and pasting it in other canvas?

1

There are 1 answers

0
Bhavik Shah On BEST ANSWER

Instead of getSubRaster() I used Raster#getSubCanvas and Context#drawImage to paste in new canvas. So in short

canvasSrc = raster.getSubCanvas(rect);
destinationCanvasContext.drawImage(canvasSrc,0,0);