ChatGPT解决这个技术问题 Extra ChatGPT

Drawing an image from a data URL to a canvas

How can i open an image in a Canvas ? which is encoded

I am using the

var strDataURI = oCanvas.toDataURL(); 

The output is the encoded base 64 image. How can i draw this image on a canvas?

I want to use the strDataURI and create the Image ? Is it poosible ?
If its not then what possibly can be the solution for loading the image on a canvas ?

Its not working in this case:: jsfiddle.net/V92Gn/5376

C
Community

Given a data URL, you can create an image (either on the page or purely in JS) by setting the src of the image to your data URL. For example:

var img = new Image;
img.src = strDataURI;

The drawImage() method of HTML5 Canvas Context lets you copy all or a portion of an image (or canvas, or video) onto a canvas.

You might use it like so:

var myCanvas = document.getElementById('my_canvas_id');
var ctx = myCanvas.getContext('2d');
var img = new Image;
img.onload = function(){
  ctx.drawImage(img,0,0); // Or at whatever offset you like
};
img.src = strDataURI;

Edit: I previously suggested in this space that it might not be necessary to use the onload handler when a data URI is involved. Based on experimental tests from this question, it is not safe to do so. The above sequence—create the image, set the onload to use the new image, and then set the src—is necessary for some browsers to surely use the results.


Using onload handler is definitely a good idea. It might take a while to load the image so it's better to play it safe. :)
@bebraw Let's see about that for sure: stackoverflow.com/questions/4776670/… :)
@Phrogz it gives me an error: var ctx = myCanvas.getContext('2d'); just copy/past your code to test
@jepser Do you have a canvas element on your page with that id? Have you ensured that myCanvas is not null? If you still have trouble, post your own question, or come to the JavaScript chat channel.
@DavidMurdoch Great information. Do you have a Chromium bug that you could link to, so that users will know when the above statement is no longer true?
R
Raphael C
function drawDataURIOnCanvas(strDataURI, canvas) {
    "use strict";
    var img = new window.Image();
    img.addEventListener("load", function () {
        canvas.getContext("2d").drawImage(img, 0, 0);
    });
    img.setAttribute("src", strDataURI);
}

j
joe

Just to add to the other answers: In case you don't like the onload callback approach, you can "promisify" it like so:

let url = "data:image/gif;base64,R0lGODl...";
let img = new Image();
await new Promise(r => img.onload=r, img.src=url);
// now do something with img

AAAh THANK you for this! I wanted to put a PNG onto a canvas inside a function, but it returned before the img.onload function had run. Using await solved that.
佚名

Perhaps this fiddle would help ThumbGen - jsFiddle It uses File API and Canvas to dynamically generate thumbnails of images.

(function (doc) {
    var oError = null;
    var oFileIn = doc.getElementById('fileIn');
    var oFileReader = new FileReader();
    var oImage = new Image();
    oFileIn.addEventListener('change', function () {
        var oFile = this.files[0];
        var oLogInfo = doc.getElementById('logInfo');
        var rFltr = /^(?:image\/bmp|image\/cis\-cod|image\/gif|image\/ief|image\/jpeg|image\/jpeg|image\/jpeg|image\/pipeg|image\/png|image\/svg\+xml|image\/tiff|image\/x\-cmu\-raster|image\/x\-cmx|image\/x\-icon|image\/x\-portable\-anymap|image\/x\-portable\-bitmap|image\/x\-portable\-graymap|image\/x\-portable\-pixmap|image\/x\-rgb|image\/x\-xbitmap|image\/x\-xpixmap|image\/x\-xwindowdump)$/i
        try {
            if (rFltr.test(oFile.type)) {
                oFileReader.readAsDataURL(oFile);
                oLogInfo.setAttribute('class', 'message info');
                throw 'Preview for ' + oFile.name;
            } else {
                oLogInfo.setAttribute('class', 'message error');
                throw oFile.name + ' is not a valid image';
            }
        } catch (err) {
            if (oError) {
                oLogInfo.removeChild(oError);
                oError = null;
                $('#logInfo').fadeOut();
                $('#imgThumb').fadeOut();
            }
            oError = doc.createTextNode(err);
            oLogInfo.appendChild(oError);
            $('#logInfo').fadeIn();
        }
    }, false);
    oFileReader.addEventListener('load', function (e) {
        oImage.src = e.target.result;
    }, false);
    oImage.addEventListener('load', function () {
        if (oCanvas) {
            oCanvas = null;
            oContext = null;
            $('#imgThumb').fadeOut();
        }
        var oCanvas = doc.getElementById('imgThumb');
        var oContext = oCanvas.getContext('2d');
        var nWidth = (this.width > 500) ? this.width / 4 : this.width;
        var nHeight = (this.height > 500) ? this.height / 4 : this.height;
        oCanvas.setAttribute('width', nWidth);
        oCanvas.setAttribute('height', nHeight);
        oContext.drawImage(this, 0, 0, nWidth, nHeight);
        $('#imgThumb').fadeIn();
    }, false);
})(document);

g
gabrielrincon

Mixing the answers I do.

function drawDataURIOnCanvas(strDataURI, canvas) {
   var img = new window.Image();
   img.addEventListener("load", function () {
     canvas.getContext("2d").clearRect(0, 0, canvas.width, canvas.height);
     canvas.width = img.width;
     canvas.height = img.height;
     canvas.getContext("2d").drawImage(img, 0, 0, img.width, img.height);
   });

   img.setAttribute("src", strDataURI);
}

H
Hitesh Sahu

You might wanna clear the old Image before setting a new Image.

You also need to update the Canvas size for a new Image.

This is how I am doing in my project:

    // on image load update Canvas Image 
    this.image.onload = () => {

      // Clear Old Image and Reset Bounds
      canvasContext.clearRect(0, 0, this.canvas.width, this.canvas.height);
      this.canvas.height = this.image.height;
      this.canvas.width = this.image.width;

      // Redraw Image
      canvasContext.drawImage(
        this.image,
        0,
        0,
        this.image.width,
        this.image.height
      );
    };

u
user475434

in javascript , using jquery for canvas id selection :

 var Canvas2 = $("#canvas2")[0];
        var Context2 = Canvas2.getContext("2d");
        var image = new Image();
        image.src = "images/eye.jpg";
        Context2.drawImage(image, 0, 0);

html5:

<canvas id="canvas2"></canvas>

This does not answer the OP's question related to the dataURL.
Why would you use jQuery to select the canvas? Is typing document.getElementById() too much work?
This code works, though it is not related to question