0

我正在试验 Raymond Camden 的水印代码以及 Phonegap 相机 API 的示例。

相机效果很好。

然而,

Uncaught ReferenceError: canvas is not defined

显示在 LogCat 中。

我试图将变量放在函数中以及全局中。但错误仍然出现。我的代码如下:

<!DOCTYPE html>
<head>
<script type="text/javascript" charset="utf-8" src="cordova-2.7.0.js"></script>
<link rel="stylesheet" type="text/css" href="jquery/css/jquery.mobile-1.3.1.min.css"/>
<script type="text/javascript" charset="utf-8" src="jquery/jquery-1.9.1.min.js"></script>
<script type="text/javascript" charset="utf-8" src="jquery/jquery.mobile-1.3.1.min.js"><script>
<script type="text/javascript" charset="utf-8">

var watermark;
var canvasDOM;
var canvas;


document.addEventListener("deviceready",onDeviceReady,false);


function onDeviceReady() {

} </script>

<script type="text/javascript" charset="utf-8">

    canvasDOM = $("myCanvas")[0];
    canvas = canvasDOM.getContext("2d");

    watermark = new Image();
    watermark.src = "q1.jpg";

    function cybershot() {
    navigator.camera.getPicture(camSuccess, camError, {quality: 75, targetWidth: 400, targetHeight: 400, destinationType: Camera.DestinationType.FILE_URI});
    }

    function camError(e) {
    console.log("Camera Error");
    console.log(JSON.stringify(e));
    }


    function camSuccess(picuri) {
    console.log("Camera Success");

    var img = new Image();
    img.src=picuri;

    img.onload = function(e) {
        canvas.drawImage(img, 0, 0);
        canvas.drawImage(watermark, canvasDOM.width-watermark.width, canvasDOM.height - watermark.height);
    }


    }


</script>


<style>
#myCanvas {
    width: 400px;
    height: 400px;
}
</style>


  </head>
  <body>
  <h1>Watermark Camera</h1>


  <button onclick="cybershot();">Capture Photo</button> <br>


  <p/>

  <canvas id="myCanvas"></canvas>
</body>
</html>
4

2 回答 2

2

解决方案

这段代码有错误。

使用的 Javascript 必须放在onDeviceReady()函数内。它相当于经典的jQuery文档就绪。

在这种情况下,javascriptHEADBODY内容加载到DOM. onDeviceReady()将延迟其执行,直到所有内容都加载到DOM.

固定代码

您的 javascript 应如下所示:

var canvas;
var watermark;

document.addEventListener("deviceready",onDeviceReady,false);  

function onDeviceReady() {
    canvasDOM = $("myCanvas")[0];
    canvas = canvasDOM.getContext("2d");
    
    watermark = new Image();
    watermark.src = "q1.jpg";    
} 

function cybershot() {
    navigator.camera.getPicture(camSuccess, camError, {quality: 75, targetWidth: 400, targetHeight: 400, destinationType: Camera.DestinationType.FILE_URI});
}

function camError(e) {
    console.log("Camera Error");
    console.log(JSON.stringify(e));
}


function camSuccess(picuri) {
    console.log("Camera Success");
    
    var img = new Image();
    img.src=picuri;
    
    img.onload = function(e) {
        canvas.drawImage(img, 0, 0);
        canvas.drawImage(watermark, canvasDOM.width-watermark.width, canvasDOM.height - watermark.height);
    }  
}
于 2013-06-21T09:27:41.167 回答
1

尝试将这部分(脚本块的全部内容)移动canvasDOM = $("myCanvas")[0];$(document).ready(function(){ });

于 2013-06-21T08:03:56.787 回答