Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to draw on multiple canvases at once?

All of my canvas drawing functions start something like this:

function drawMe(){

    var canvas = document.getElementById('canvas-id');

    var ctx = null;

    ctx = canvas.getContext('2d');

    ...
}

However I now want to draw the same image on a (variable) number of canvases, is there some alternative to getElementById() (perhaps in jQuery?) which can be used to easily grab more than one at once?

Thanks!

Josh

like image 225
Joshua Avatar asked Aug 04 '11 16:08

Joshua


People also ask

Can you have multiple canvas?

Welcome to the Canvas Community. And Yes, you can have multiple Canvas accounts associated in the app.

Can we use multiple canvas in html?

A webpage may contain multiple canvas elements. Each canvas may have an id using which you may target a specific canvas through JavaScript. Each canvas element has a 2D Context. This again has objects, properties, and methods.


1 Answers

drawing to multiple canvases will be extremely inefficient, because rendering is one of most expensive operations you can do.

what you want to do is to use buffer. you can simply draw from one canvas to another.

var canvas1 = document.getElementById("canvas1");
var canvas2 = document.getElementById("canvas2");

var ctx1 = canvas1.getContext("2d");
var ctx2 = canvas2.getContext("2d");

ctx1.fillStyle = "black";
ctx1.fillRect(10, 10, 10, 10);

ctx2.drawImage(canvas1, 0, 0);

here's a fiddle.

remember, you only need to call ctx.drawImage once - after you're done with all drawing on first canvas.

like image 67
wildcard Avatar answered Sep 17 '22 04:09

wildcard