开发者

Display canvas image from one canvas to another canvas using base64

开发者 https://www.devze.com 2023-01-24 10:20 出处:网络
E.g. var new = canvas.toDataURL(\"image/png\"); I want the base64 that is present in this new variable to be displayed into 2nd canvas element that is present. But it does not display the base64 imag

E.g. var new = canvas.toDataURL("image/png");

I want the base64 that is present in this new variable to be displayed into 2nd canvas element that is present. But it does not display the base64 image using drawimage meth开发者_StackOverflow中文版od. It works if I use say image.png


You shouldn't use base64 to copy the canvas. You can pass the source canvas into the destination canvas' context method, drawImage.

Otherwise you will suffer a serious performance hit. See my jsperf test at http://jsperf.com/copying-a-canvas-element.

drawImage() will accept a Canvas as well as an Image object.

Try this:

//grab the context from your destination canvas
var destCtx = destinationCanvas.getContext('2d');

//call its drawImage() function passing it the source canvas directly
destCtx.drawImage(sourceCanvas, 0, 0);


  1. First create an Image Element & give the Image source as the cached .DataURL() source

  2. Using the Image <img /> (which we created earlier) draw the Image Content onto second Canvas element

E.g.:

window.onload = function() { 
    var canvas1 = document.getElementById('canvas1');
    var canvas2 = document.getElementById('canvas2');
    var ctx1    = canvas1.getContext('2d');
    var ctx2    = canvas2.getContext('2d');

    var src     = canvas.toDataURL("image/png"); // cache the image data source

    var img     = document.createElement('img'); // create a Image Element
    img.src     = src;   //image source

    ctx2.drawImage(img, 0, 0);  // drawing image onto second canvas element
};
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号