[英]Create a canvas with background image, dynamically update the text, then save the canvas?
我試圖用背景圖像和文本創建畫布,單擊按鈕時通過用戶輸入更新文本內容,然后將更新后的畫布轉換為圖像以保存它。
這是我一直在做的一個例子: 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);
}
如果不分配背景圖像,則可以使用以下代碼將畫布轉換為圖像:
function convertCanvasToImage(canvas) {
var image = new Image();
image.src = canvas.toDataURL("image/png");
return image;
}
然后保存:
function downloadCanvas(link, canvasId, filename) {
link.href = document.getElementById(canvasId).toDataURL();
link.download = filename;
}
但是,一旦動態更新,就無法將圖像轉換為png進行保存。 我嘗試過重新設置背景圖片,但這也不起作用。
編輯並添加了我得到的錯誤:“未捕獲的SecurityError:無法在'HTMLCanvasElement'上執行'toDataURL':可能無法導出污染的畫布。”
任何幫助,將不勝感激。
來自先前的答案
當將圖像從與當前域不同的域加載到畫布上時,就會出現受污染的畫布。 之后,畫布將無法保存到數據URL。
解決方案:
將所有與頁面相關的文件(.html,.jpg,.js,.css等)放在桌面上(而不是子文件夾中)。
將您的圖像發布到支持跨域共享的網站(例如dropbox.com)。 確保將圖像放入Dropbox的公用文件夾中,並在下載圖像時設置交叉原點標記(var img = new Image(); img.crossOrigin =“ anonymous” ...)
在開發計算機上安裝Web服務器(IIS和PHP Web服務器都有免費版本,它們可以在本地計算機上正常運行)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.