Create a canvas with background image, dynamically

2019-09-19 10:33发布

问题:

I'm trying to create a canvas with a background image and text, update the text content via user input on button click, then convert that updated canvas to an image in order to save it.

Here's an example of what I've been doing: https://jsfiddle.net/qrzd395p/

var c = document.getElementById('canvas');
var context = c.getContext('2d');
var backgroundImage = new Image();

backgroundImage.onload = function() {
   // Once the image has finished loading, draw the 
   // image and then the text.
   DrawScreen();
   DrawText();
};
backgroundImage.src = "http://lorempixum.com/200/200/";

function DrawScreen() {
   context.drawImage(backgroundImage, 0, 0);
}

function DrawText() {
   context.fillStyle = "red";
   context.font = "18px sans-serif";
   context.textBaseline = 'top';
   context.fillText("This is a test", 50, 100);
}

If I don't assign a background image I can convert the canvas to an image using the following code:

function convertCanvasToImage(canvas) {
   var image = new Image();
   image.src = canvas.toDataURL("image/png");
   return image;
}

Then to save:

function downloadCanvas(link, canvasId, filename) {
   link.href = document.getElementById(canvasId).toDataURL();
   link.download = filename;
}

However once I've updated it dynamically I can't convert the image to a png for saving. I've tried re-setting the background image but this does not work either.

Edited to add the error I get: "Uncaught SecurityError: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported."

Any help would be appreciated.

回答1:

From a previous answer

A tainted canvas occurs when images are loaded onto a canvas from a different domain than a current one. After that the canvas cannot be saved to a data URL.

Solutions:

Put all page related files (.html, .jpg, .js, .css, etc) on your desktop (not in sub-folders).

Post your images to a site that supports cross-domain sharing (like dropbox.com). Be sure you put your images in dropbox's public folder and also set the cross origin flag when downloading the image (var img=new Image(); img.crossOrigin="anonymous" ...)

Install a webserver on your development computer (IIS and PHP web servers both have free editions that work nicely on a local computer).