HTML5画布-绘制的线条很快消失了

时间:2018-07-25 09:17:36

标签: javascript html5 canvas

我有两个画布,一个在另一个上。

<div class="center">
  <canvas id="imgcanvas" style="position:absolute;margin:0 0 0 0;z-index:1"></canvas>
  <canvas id="drawcanvas" style="position:absolute;margin:0 0 0 0;z-index:2"></canvas>
</div>

在画布下面,我有一个水平的缩略图板。单击缩略图后,单击的图像将在图像画布中呈现。我正在使用drawcanvas在画布上绘制线条。绘制线的坐标存储在localStorage中。

在单击缩略图时,同时加载图像,我试图绘制从localStorage获取坐标的线。但是,线条被绘制并在一瞬间消失。

以下是代码:

//clicked_id is returned by the thumbnail

function clickedImage(clicked_id) {
  localStorage.setItem('sel_id', clicked_id);
  //Get the complete path of the image
  var clickedImg = document.getElementById(clicked_id).src;
  var activeImg = document.getElementById(clicked_id).src;

  //store the complete path
  localStorage.setItem("activeImg",activeImg);
  var clickedImg = basename(clickedImg,"/");
  localStorage.setItem("clickedImage", clickedImg);
  var clickedImg = clickedImg.replace(/^.*[\\\/]/, '');

  //draw lines on canvas
  var canvas = document.getElementById("imgcanvas");
  var regcanvas = document.getElementById("drawcanvas");
  var ctx = canvas.getContext("2d");
  var ctxr = regcanvas.getContext("2d");
  var arr = new Array();
    //Perform calculations to get the fourth coordinate
    arr = fourthCoord(getArray(arr));
    for (var i = 0; i < arr.length; i++) {
      if (arr[i][0] === clickedImg) {
        first.x = arr[i][3];
        first.y = arr[i][4]; 
        second.x = arr[i][5]; 
        second.y = arr[i][6]; 
        third.x = arr[i][7]; 
        third.y = arr[i][8]; 
        fourth.x = arr[i][9]; 
        fourth.y = arr[i][10]; 
        ctxr.lineCap = "round";
        ctxr.lineWidth = 3;
        ctxr.strokeStyle = '#f4d03f';
        ctxr.beginPath();
        ctxr.moveTo(first.x,first.y);
        ctxr.lineTo(second.x,second.y);
        ctxr.lineTo(third.x,third.y);
        ctxr.lineTo(fourth.x,fourth.y);
        ctxr.lineTo(first.x,first.y);
        ctxr.stroke();
        console.log(first,second,third,fourth);
      }
    }

  //Load the image
  var thumbNails = document.getElementById("loaded_img_panel");
  var pic = new Image();
  pic.onload = function() {
    canvas.width = pic.width;
    canvas.height = pic.height;
    regcanvas.width = pic.width;
    regcanvas.height = pic.height;
    ctx.drawImage(pic, 0,0)
  }

  thumbNails.addEventListener('click',function(event) {
    pic.src = event.target.src;  
  });
}

getArray()函数获取行的坐标。我在示例画布上使用了相同的代码,在画布上单击(而不是单击图像)可以绘制线条。但是,在此应用程序上,线条被绘制(我可以看到不到一秒钟的时间)然后消失了。

审判1:

我在thumbNail的onclick中调用了两个函数-clickedImage()和drawAnnotations()。我将所有与绘制线有关的代码移到了drawAnnotations()中。这没用。

审判2:

在第一个函数中,我在缩略图的mousedown事件上调用了clickedImage(),在缩略图的mouseup事件上调用了drawAnnotations()。这也行不通。

试验3:

我创建了一个window.addEventListener ...并在加载时调用了drawAnnotation函数

window.addEventListener("DOMContentLoaded", function(event) {
    document.getElementById('drawcanvas').addEventListener("load", drawAnnotations);
});

这也行不通...意味着...它画了线...但是很快就消失了。

0 个答案:

没有答案