Двойное отображение элемента холста

Нарисованные линии появляются не только в 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);
}    

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>

Ответы

Ответ 1

Я решил проблему, позиционируя холст в абсолютном, а не относительном позиционировании, как упоминалось в https://github.com/jquery/jquery-mobile/issues/5107

Ответ 2

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);
}

EDIT: я немного поработал, похоже, проблема состоит в том, что событие вызывается дважды. Если вы можете это подтвердить, мы можем найти способ обхода.

Ответ 3

попробуйте окружить холст с помощью div и применить переполнение CSS: спрятаться в этом div.