双重显示画布元素

Go *_*ami 15 javascript jquery canvas cordova

绘制的线条不仅出现在Canvas-Element中,而且还出现在页面顶部,再次显示.

发生触摸事件时会发生这种情况.

在这里您可以找到源代码和结果(使用PhoneGap和Jquery Mobile).

有谁知道这个错误的原因是什么?

http://gomami.ch/bugs/screenshot.png http://gomami.ch/bugs/screenshot.png

JavaScript(在包含到jQuery/PhoneGap之后的头文件中加载):

//*********************************************************
// Wait for Cordova to Load
//*********************************************************
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
  canvas("aufprallstelleA","test");
}

// function to setup a new canvas for drawing
function canvas(canvas, element){
    //define and resize canvas
    width = $(window).width();
    width = (width/100)*90;
    height = width/1.6901408;
    $("#content").width(width);
    $("#"+element).height(height);
    $("#"+element).width(width);
    var html = 'This is de Canvas field wehre you can draw<br><canvas id="'+
               canvas+'" width="'+width+'" height="'+height+
               '" style="border:black solid 1px;background-size: 100%; background-repeat: no-repeat;background-image: url(\'images/allgemein/aufprallstelle.PNG\');"></canvas>';
    $("#"+element).html(html);      
    // setup canvas
    ctx=document.getElementById(canvas).getContext("2d");
    ctx.strokeStyle = "red";
    ctx.lineWidth = 5;          
    // setup to trigger drawing on mouse or touch
    $("#"+canvas).on("touchstart", start);
    $("#"+canvas).on("touchmove", move);
}

function start(e){
    e = e.originalEvent;
    x = e.changedTouches[0].pageX-20;
    y = e.changedTouches[0].pageY-$(this).position().top;
    ctx.moveTo(x,y);
}

function move(e){
    e.preventDefault();
    e = e.originalEvent;
    x = e.changedTouches[0].pageX-20;
    y = e.changedTouches[0].pageY-$(this).position().top;
    ctx.lineTo(x,y);
    ctx.stroke();
}

function clearcanvas(id) {
    var canvas = document.getElementById(id);
    var context = canvas.getContext('2d');
    context.clearRect(0, 0, canvas.width, canvas.height);
}    
Run Code Online (Sandbox Code Playgroud)

HTML:

<div data-role="page" id="main">
  <div data-role="header" id="header">
    <div id="header_anzeige">
    </div>
  </div>
  <div data-role="content" id="content" >
    <div id="test" style="margin-top:265px;"></div><br>
    Hello, this is JQuery Mobile running in PhoneGap 2
  </div>   
</div> 
copyright
</div>
</div>
Run Code Online (Sandbox Code Playgroud)

Mou*_*ach 0

onDeviceReady可能被调用两次。您是否尝试过将画布保存在变量中以避免创建两次?请注意,第一个被调用的可能是有问题的,因此窗口大小很可能是错误的。

var theCanvas;
function onDeviceReady() {
    if(!theCanvas){
        canvas("aufprallstelleA","test");
    }
}

function canvas(canvas, element){
    //define and resize canvas
    width = $(window).width();

    [...]

    $("#"+canvas).on("touchmove", move);
    return $("#"+canvas);
}
Run Code Online (Sandbox Code Playgroud)

编辑:我做了一些研究,问题似乎出在事件被调用两次。如果您能确认这一点,我们可以寻找解决方法。