Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add image to canvas using paper JS

I used normal javascript to add image to canvas and this is the code

var canvas = document.getElementById('canvas');
context = canvas.getContext('2d');

canvas_image();

function canvas_image(){
    can_img = new Image();
    can_img.src = 'Chrysanthemum.jpg';
    can_img.onload = function(){
    context.drawImage(can_img, 100, 100);   
    }
}

How can i add image to canvas using paperJS library?

like image 767
chiyango Avatar asked Jun 01 '13 17:06

chiyango


2 Answers

Quoting from the paperjs.org tutorial on rasters:

Images need to already be loaded when they are added to a Paper.js project. Working with local images or images hosted on other websites may throw security exceptions on certain browsers.

So you need an image somewhere that is preferably visually hidden:

<img id="mona" class="visuallyhidden" src="mona.jpg" width="320" height="491">

And the PaperScript code could look like this:

// Create a raster item using the image tag with id="mona"
var raster = new Raster('mona');

Then you can reposition, scale or rotate like so:

// Move the raster to the center of the view
raster.position = view.center;

// Scale the raster by 50%
raster.scale(0.5);

// Rotate the raster by 45 degrees:
raster.rotate(45);

And here is a paperjs.org sketch to play with.

like image 56
Christoph Avatar answered Nov 14 '22 21:11

Christoph


First, If you want to work with JavaScript directly look at this tutorial. Once you understand it, you would have something like this to load image in raster

paper.install(window);
window.onload = function() {
    // Setup directly from canvas id:
    paper.setup('myCanvas');
    var raster = new paper.Raster({source: 'Chrysanthemum.jpg', position: view.center});
}
like image 38
Bhavik Shah Avatar answered Nov 14 '22 21:11

Bhavik Shah