8

I would like to capture a small part of a canvas as a bitmap. Is that possible? This is so that I can replace it after I draw another bitmap on that area. Once I am done with the bitmap I would like to replace the small bit of canvas that I drew on with the original piece.

Thanks!

fresskoma
  • 25,481
  • 10
  • 85
  • 128

3 Answers3

9

The drawImage() method of contexts allows you to use an existing canvas as the source. It also allows you to specify sub-regions of the source "image" to draw. You can also create a new canvas element programmatically. Combine these, and you can create your own offscreen buffers and blit to/from them without needing to go through getImageData()/putImageData() or data URLs.

I've put an example of this online.

Note that while the example happens to append the dynamically-created canvas to the document so that you can see it (line 29 of the source), this is not necessary. Canvas elements created in the document function whether attached to the hierarchy or not.

In short:

function copyCanvasRegionToBuffer( canvas, x, y, w, h, bufferCanvas ){
  if (!bufferCanvas) bufferCanvas = document.createElement('canvas');
  bufferCanvas.width  = w;
  bufferCanvas.height = h;
  bufferCanvas.getContext('2d').drawImage( canvas, x, y, w, h, 0, 0, w, h );
  return bufferCanvas;
}

Edit: I benchmarked this technique versus getImageData/putImageData; if speed is important, use drawImage for blitting regions. Here's what I saw:


(source: phrogz.net)

Benchmarks performed by saving and restoring a 125x180 region 10,000 times on OS X on a 2.8GHz Core i7 MacBook Pro. Your mileage may vary. Specifically, saving/restoring regions that are either much larger or smaller may result in different relative performance.

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
Phrogz
  • 296,393
  • 112
  • 651
  • 745
  • Though, if you need to save the region of the canvas long term (serialized and sent to the server), `getImageData()` and `toDataURL()` are your friends. – Phrogz Dec 27 '10 at 05:40
  • how did u performed the benchmark tests ?? I mean what are the tools you used –  Dec 31 '11 at 17:28
  • @Avinash See [the benchmark page](http://phrogz.net/tmp/canvas_copy_benchmark.html). (The results show up in the log, somewhat confusingly named.) – Phrogz Dec 31 '11 at 17:51
8

you can do this using .getImageData() and .putImageData()

Example

var canvas, ctx, img, imgd, col;
window.onload = function () {
    canvas = document.getElementById('canvas');
    ctx = canvas.getContext('2d');
    col = {
        0: '#000',
        .25: '#0099f9',
        .55: '#03f',
        1: '#000'
    };
    img = document.getElementById('img');
    var w = h = canvas.width = canvas.height = 200;

    var grad = ctx.createRadialGradient(w / 2, w / 2, 0, w / 2, w / 2, h);
    for (var i in col) {
        grad.addColorStop(i, col[i]); //just a funny mess, please don't bother :)
    }

    ctx.fillStyle = grad;
    ctx.fillRect(0, 0, w, h);
    imgd = ctx.getImageData(50, 50, 20, 20); //caching the image Data

}

function draw() {
    ctx.drawImage(img, 50, 50, 20, 20); //drawing Image on to canvas
}

function redraw() {
    ctx.putImageData(imgd, 50, 50, 20, 20); //redraw the cached Image Data
}

and a simple Online Example, just you :)

Try it Here

  • 1
    getImageData() & putImageData() are the proper way(s) you should do this - not using hidden-element hacks, when this takes advantage of the API's low-level scope, so kudos to this answer. :) – SikoSoft Apr 25 '11 at 13:47
2

have a look at a similar question here How to Copy Contents of One Canvas to Another Canvas Locally

What i suggest is write somthing like

var canvas1 = document.getElementById('canvas1');
var src     = canvas1.toDataURL("image/png"); // cache the image data source`

to save image in a variable and then retrive it later with

var img     = document.createElement('img'); // create a Image Element
img.src     = src;   //image source
var ctx1    = canvas1.getContext('2d');
ctx2.drawImage(img, 0, 0);  // drawing image onto second canvas element

Taken from here

Community
  • 1
  • 1
Shekhar_Pro
  • 18,056
  • 9
  • 55
  • 79