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 wa开发者_如何学JAVAnt 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
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.
With jQuery, if you do $('.blah') you will get all elements of the class 'blah'. So if you give all your canvases that class you could merely iterate through them all and draw on each one at that point.
It is ideal to get all of the contexts only once though, so unless drawMe
is only called once, you should collect all the contexts just once and then pass that array into drawMe
each time it is called.
Interesting... I'm sure it's not the best solution (I'm not entirely sure it'll work!), and it assumes a class by which to identify your canvas, but try this:
var canvases, contexts, imgdata = 0;
function init() {
canvases = document.getElementsByClassName('cvs-class');
contexts = [];
for(var i = 0; i < canvases.length; i++) {
contexts[i] = canvases[i].getContext('2d'); //initialize each canvas with context.
}
}
function drawToCanvas() {
// Do your drawing on canvases[0];
imgdata = contexts[0].getImageData(0,0,canvases[0].width,canvases[0].height);
paintToAllContexts();
}
function paintToAllContexts() {
for(var i=0; i<canvases.length; i++) {
contexts[i].putImageData(imgdata,0,0);
}
}
function document.getElementsByClassName(class) {
var nodes = [];
var cl = new RegExp('\\b'+cl+'\\b');
var el = this.getElementsByTagName('*');
for(var i = 0; i < el.length; i++) {
var cls = el[i].className;
if(cl.test(cls)) nodes.push(el[i]);
}
return nodes;
}
If you are drawing a complex image on to several canvases, it might be better to:
- Draw a complex image to the first canvas.
- Paste that canvas to the other canvases via
drawImage()
(which can take a canvas parameter).
This way you just copy the image pixels rather than drawing something complicated repeatedly. If it's just a single image, though, it's probably better just to draw that directly like the other answers propose.
Give each canvas a class and loop through each canvas with the class.
var allCanvases = document.getElementsByTagName('canvas');
精彩评论