简体   繁体   中英

Multiple Dynamic Canvas Elements?

I have some code dynamically generating canvas elements from images using jquery and want to apply a single drawing context to each and all of these elements using document.getElementsByName or a similar method, is this possible? Here's my code so far:

$('#imagebox img').each(function(){

      var width = $(this).width();
      var height = $(this).height();

        $('<canvas/>', {
        name: 'canv',
        css: {
          margin: '0px',
          background: '#FF0000',
          float: 'left',
          width: width,
          height: height
        }
      }).appendTo('#main'); 

          // Get the canvas element and its drawing context
        var canvas = document.getElementsByName('canv');
        var context = canvas.getContext('2d');

        /*
        |---------------------
        | Origin: Top Left
        | End: Bottom Right
        |---------------------
        */

        context.beginPath();
        context.moveTo(0, 0);
        context.lineTo(canvas.width, canvas.height);
        context.stroke();

        /*
        |---------------------
        | Origin: Top Right
        | End: Bottom Left
        |---------------------
        */

        context.save();
        context.beginPath();
        context.moveTo(canvas.width, 0);
        context.lineTo(0, canvas.height);
        context.stroke();
        context.restore();

    });

Yes, it is certainly possible to achieve the effect you desire.

You simply draw onto one of the canvas contexts, and then use drawImage(originalContext,0,0) on all the other canvas contexts in order to make a complete copy.

The original canvas (the one that you are doing all the drawing operations on) doesn't even have to be on the page. It could be created just in code if you wanted, and all the ones on the page are just drawImage 's of that canvas context.

Here's an exmaple of two canvases "sharing" a context. All the stuff is drawn on canvas1, and then I scale a smaller canvas2 and draw canvas1's context onto it:

http://jsfiddle.net/U6QLN/

is this possible?

No, it's not possible.

A Canvas element is just like any HTML element - each instance can only appear at most once within the HTML page.

Furthermore, each Canvas has exactly one Context, and Contexts cannot be shared.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM