2016-02-28 18 views
1

我是一個JavaScript初學者。 我想導出爲裝飾的PNG圖像(正在用fillText繪製一些文本)的畫布。如何導出裝飾html5功能的canvas圖像

但我不能因爲以下錯誤。

Script from origin 'file://' has been blocked from loading by Cross-Origin Resource Sharing policy: Invalid response. Origin 'null' is therefore not allowed access. 

我很高興如果你有一些建議。

下面是我的源代碼

的index.html

<!DOCTYPE html> 
<html> 
<head> 
    <meta charset="utf-8"> 
    <script src="myscript.js" crossorigin="anonymous"></script> 
</head> 
<body> 
<h1>draw text to loaded image</h1> 
<form> 
<input type="button" value="draw on canvas" onclick="draw()"> 
</form> 
<canvas id="mycanvas" width="400" height="400"> 
</canvas> 
<!-- <form> 
<input type="button" value="export to image" onclick="chgImg()"> 
</form> --> 
<div><img id="newImg"></div> 
</body> 
<script src="myscript.js"></script> 
</html> 

myscript.js

var canvas = document.getElementById('mycanvas'); 
var ctx = canvas.getContext('2d'); 

function draw(){ 
    var img = new Image(); 
    //load local image 
    img.src = 'test.png'; 
    img.onload = function() { 
    ctx.globalCompositeOperation = 'destination-over'; 
    var pattern = ctx.createPattern(img, 'no-repeat'); 
    ctx.fillStyle = pattern; 
    ctx.drawImage(img, 10, 10); 
    } 
    ctx.font = 'bold 20px Verdana'; 
    ctx.textAlign = 'left'; 
    ctx.fillStyle = 'red'; 
    ctx.fillText('test', 20, 20, 200); 
    var dataURL = canvas.toDataURL(); 
    document.getElementById("newImg").src = dataURL; 
    console.log(dataURL); 
    chgImg(); 
} 

// export to png 
function chgImg() { 
    var png = canvas.toDataURL(); 
    document.getElementById("newImg").src = png; 
} 
+0

很可能你會將頁面加載爲本地文件,這會在大多數瀏覽器中引起安全問題。您必須將其放置在Web服務器上。 – hindmost

+0

謝謝@你最好的建議。 我打算將它製作成帶電子的桌面應用程序。所以,我不想使用服務器。你有什麼好主意嗎? – mofuty

回答

0

我認爲這個問題是裝載test.png從本地文件違反了相同的原點策略,因此瀏覽器不會讓您提取合併的圖像。

您可以嘗試的一個選項是從data:url加載test.png。

另一個選項可能是運行本地服務器,如其中一個註釋所示。既然你想用電子來運行它,我會首先檢查實際運行在電子中的文件是否與文件運行有相同的限制:

+0

Hausein謝謝您的建議!我想首先檢查電子運行的最佳做法。 – mofuty