为什么这两个javascript文件不能同时运行?他们为什么会发生冲突/覆盖?

时间:2015-04-07 21:15:19

标签: javascript jquery html css canvas

为什么会这样?左边假设是白板,右边的画布是否包含条形图?基本上javascript代码的前半部分不会执行。 我对调试知之甚少。但是我有一个概念,即“窗口载荷”。可能是一个问题。我希望两个画布功能,条形图显示和草图功能。



var mycanvas, mycontext;
var SnapCanvas, mycontext;
var bchart, mycontext;

var drawing = false;

function findPos(obj) {
  var curleft = curtop = 0;
  if (obj.offsetParent) {
    do {
      curleft += obj.offsetLeft;
      curtop += obj.offsetTop;
    } while (obj = obj.offsetParent);

    return [curleft, curtop];
  }
}

function getMouseCoords(event) {
  if (!event) var event = window.event;
  var posx = 0;
  var posy = 0;
  if (event.pageX || event.pageY) {
    posx = event.pageX;
    posy = event.pageY;
  } else if (event.clientX || event.clientY) {
    posx = event.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
    posy = event.clientY + document.body.scrollTop + document.documentElement.scrollTop;
  }

  var totaloffset = findPos(mycanvas);
  var totalXoffset = totaloffset[0];
  var totalYoffset = totaloffset[1];
  var canvasX = posx - totalXoffset;
  var canvasY = posy - totalYoffset;

  // return coordinates in an array
  return [canvasX, canvasY];
}

function draw(e) {
  if (drawing) {
    var coords = getMouseCoords(e);
    mycontext.lineTo(coords[0], coords[1]);
    mycontext.stroke();
    if (e.shiftKey) {
      mycontext.fill();
    }
  }
}

function startdraw(e) {
  drawing = true;
  mycontext.beginPath();
  coords = getMouseCoords(e);
  mycontext.moveTo(coords[0], coords[1]);
}

function stopdraw() {
  mycontext.closePath();
  drawing = false;
}

function reset() {
  mycontext.clearRect(0, 0, mycanvas.clientWidth, mycanvas.clientHeight);
  mycontext.strokeStyle = "black";
  var myImage = new Image();
  myImage.onload = function() {
    mycontext.drawImage(myImage, 0, 0, 333, 500);
    mycontext.save();
  }
  myImage.src = mona;
}

function downloadPanel() {
  document.getElementById('downloadpic').src = mycanvas.toDataURL();
  document.getElementById('link').href = mycanvas.toDataURL();
  document.getElementById('panel').style.display = "block";
}

function closeDownloadPanel() {
  document.getElementById('panel').style.display = "none";
}

function init() {
  mycanvas = document.getElementById("bchart");

  if (mycanvas.getContext) {
    mycontext = mycanvas.getContext("2d");
    mycanvas.onmousemove = draw;
    mycanvas.onmousedown = startdraw;
    mycanvas.onmouseup = stopdraw;
    mycanvas.onmouseout = stopdraw;
    document.getElementById("thickness").onchange = function() {
      setThickness(this.value);
    };
    document.getElementById("pencolour").onchange = function() {
      setColour(this.value);
    };
    document.getElementById("fillcolour").onchange = function() {
      setFillColour(this.value);
    };
    document.getElementById("download").onclick = downloadPanel;
    document.getElementById("clear").onclick = reset;
    document.getElementById("closepanel").onclick = function() {
      closeDownloadPanel();
      return false;
    };
    reset();
  }
}

function setThickness(x) {
  mycontext.lineWidth = x;
}

function setColour(name) {
  mycontext.strokeStyle = name;
}

function setFillColour(name) {
  mycontext.fillStyle = name;
}

window.onload = init;

// Part two

window.onload = function() {
    // chart sample data
    var colours = {
      Mon: 'red',
      Tue: 'blue',
      Wed: 'yellow',
      Thur: 'green',
      Fri: 'orange',
      Sat: 'black',
      Sun: 'brown'
    };
    var arrVisitors = new Array();
    arrVisitors[0] = "Mon, 87";
    arrVisitors[1] = "Tue, 23";
    arrVisitors[2] = "Wed, 60";
    arrVisitors[3] = "Thur, 70";
    arrVisitors[4] = "Fri, 20";
    arrVisitors[5] = "Sat, 90";
    arrVisitors[6] = "Sun, 60";

    var canvas;
    var context;
    // chart properties
    var cWidth, cHeight, cMargin, cSpace;
    var cMarginSpace, cMarginHeight;
    // bar properties
    var bWidth, bMargin, totalBars, maxDataValue;
    var bWidthMargin;
    // bar animation
    var ctr, numctr, speed;
    // axis property
    var totLabelsOnYAxis;
    // barchart constructor
    function barChart() {
        canvas = document.getElementById('SnapCanvas');
        if (canvas && canvas.getContext) {
          context = canvas.getContext('2d');
        }
        chartSettings();
        drawAxisLabelMarkers();
        drawChartWithAnimation();
      }
      // initialize the chart and bar values

    function chartSettings() {
        // chart properties
        cMargin = 15;
        cSpace = 20;
        cHeight = canvas.height - 2 * cMargin - cSpace;
        cWidth = canvas.width - 2 * cMargin - cSpace;
        cMarginSpace = cMargin + cSpace;
        cMarginHeight = cMargin + cHeight;
        // bar properties
        bMargin = 15;
        totalBars = arrVisitors.length;
        bWidth = (cWidth / totalBars) - bMargin;
        // find maximum value to plot on chart
        maxDataValue = 0;
        for (var i = 0; i < totalBars; i++) {
          var arrVal = arrVisitors[i].split(",");
          var barVal = parseInt(arrVal[1]);
          if (parseInt(barVal) > parseInt(maxDataValue))
            maxDataValue = barVal;
        }
        totLabelsOnYAxis = 10;
        context.font = "10pt Garamond";
        // initialize Animation variables
        ctr = 0;
        numctr = 100;
        speed = 10;
      }
      // draw chart axis, labels and markers

    function drawAxisLabelMarkers() {
        context.lineWidth = "2.0";
        // draw y axis
        drawAxis(cMarginSpace, cMarginHeight, cMarginSpace, cMargin);
        // draw x axis
        drawAxis(cMarginSpace, cMarginHeight, cMarginSpace + cWidth, cMarginHeight);
        context.lineWidth = "1.0";
        drawMarkers();
      }
      // draw X and Y axis

    function drawAxis(x, y, X, Y) {
        context.beginPath();
        context.moveTo(x, y);
        context.lineTo(X, Y);
        context.closePath();
        context.stroke();
      }
      // draw chart markers on X and Y Axis

    function drawMarkers() {
      var numMarkers = parseInt(maxDataValue / totLabelsOnYAxis);
      context.textAlign = "right";
      context.fillStyle = "#000";;
      // Y Axis
      for (var i = 0; i <= totLabelsOnYAxis; i++) {
        markerVal = i * numMarkers;
        markerValHt = i * numMarkers * cHeight;
        var xMarkers = cMarginSpace - 5;
        var yMarkers = cMarginHeight - (markerValHt / maxDataValue);
        context.fillText(markerVal, xMarkers, yMarkers, cSpace);
      }
      // X Axis
      context.textAlign = 'center';
      for (var i = 0; i < totalBars; i++) {
        arrval = arrVisitors[i].split(",");
        name = arrval[0];
        markerXPos = cMarginSpace + bMargin + (i * (bWidth + bMargin)) + (bWidth / 2);
        markerYPos = cMarginHeight + 10;
        context.fillText(name, markerXPos, markerYPos, bWidth);
      }
      context.save();
      // Add Y Axis title
      context.translate(cMargin + 10, cHeight / 2);
      context.rotate(Math.PI * -90 / 180);
      context.restore();
      // Add X Axis Title
    }

    function drawChartWithAnimation() {
      // Loop through the total bars and draw
      for (var i = 0; i < totalBars; i++) {
        var arrVal = arrVisitors[i].split(",");
        bVal = parseInt(arrVal[1]);
        bHt = (bVal * cHeight / maxDataValue) / numctr * ctr;
        bX = cMarginSpace + (i * (bWidth + bMargin)) + bMargin;
        bY = cMarginHeight - bHt - 2;
        drawRectangle(bX, bY, bWidth, bHt, true, colours[arrVal[0]]);
      }
      // timeout runs and checks if bars have reached the desired height
      // if not, keep growing
      if (ctr < numctr) {
        ctr = ctr + 1;
        setTimeout(arguments.callee, speed);
      }
    }

    function drawRectangle(x, y, w, h, fill, col) {
      context.beginPath();
      context.rect(x, y, w, h);
      context.closePath();
      context.stroke();
      if (fill) {
        var gradient = context.createLinearGradient(0, 0, 0, 300);
        gradient.addColorStop(0, col);
        context.fillStyle = gradient;
        context.strokeStyle = gradient;
        context.fill();
      }
    }

    barChart();
  } //]]>
&#13;
body {
  background-color: grey;
}
h1 {
  color: #FFFFFF;
  text-align: center;
  font-weight: bold;
  font-family: Arial, Helvetica, sans-serif;
  font-size: 50px;
}
canvas {
  background-color: #FFFFFF;
  position: relative;
  top: 10px;
  left: 700px;
}
#clear {
  position: relative;
  top: -32px;
  left: 210px;
}
#sketchoptions {
  position: relative;
  top: 10px;
  left: 1000px;
}
#snapdiv {
  height: 200px;
  width: 650px;
  background-color: green;
  position: absolute;
  top: 700px;
  right: 590px;
}
button {
  background: #E0E0E0;
  background-image: -webkit-linear-gradient(top, ##E0E0E0, #E0E0E0);
  background-image: -moz-linear-gradient(top, #3498db, #2980b9);
  background-image: -ms-linear-gradient(top, #3498db, #2980b9);
  background-image: -o-linear-gradient(top, #3498db, #2980b9);
  background-image: linear-gradient(to bottom, #E0E0E0, #E0E0E0);
  -webkit-border-radius: 28;
  -moz-border-radius: 28;
  border-radius: 28px;
  font-family: Arial;
  color: #000000;
  font-size: 12px;
  padding: 10px 20px 10px 20px;
  text-decoration: none;
}
#snap {
  position: relative;
  top: 120px;
  right: px;
}
#delete {
  position: relative;
  top: 120px;
  right: 250px;
}
#save li {
  list-style: none;
  margin: 0;
  padding: 0
}
#save {
  clear: both;
  padding: 10px 0;
  overflow: auto;
}
#save img {
  float: left;
  padding-right: 5px;
  padding-bottom: 5px;
}
&#13;
<!DOCTYPE>
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
  <link href="Content/Site.css" rel="stylesheet" type="text/css" />
  <link rel="stylesheet" type="text/css" href="style.css">
  <script src="variables.js"></script>



  <title>Bar Chart</title>
  <script type="text/javascript">
  </script>
  <noscript>
    This chart is unavailable because JavaScript is disabled on your computer. Please enable JavaScript and refresh this page to see the chart in action.
  </noscript>
</head>

<body onload="barChart();">
  <div id="body">
    <section class="featured">
      <div class="content-wrapper">
        <hgroup class="title">
          <h1>
                        Charts</h1>
        </hgroup>


      </div>
    </section>

    <section class="content-wrapper main-content clear-fix">
      <canvas id="bchart" height="400" width="600">
        Your browser does not support HTML5 Canvas</canvas>

      <canvas id="SnapCanvas" width="600" height="400"></canvas>


    </section>
    <div id="snapdiv"></div>
  </div>
  <div id="sketchoptions">
    <p>Stroke:

      <select id="thickness">
        <option value=1 selected>Thin</option>
        <option value=3>Medium</option>
        <option value=5>Thick</option>
      </select>


      <select id="pencolour">
        <option selected>Black</option>
        <option>Green</option>
        <option>Brown</option>
        <option>Red</option>
        <option>White</option>
        <option>Yellow</option>

      </select>
      <button id="snap" onclick="snap()">Take screenshot</button>
      <button id="delete" onclick="delete()">Delete Roll</button>

</body>

</html>
&#13;
&#13;
&#13;

4 个答案:

答案 0 :(得分:0)

你有两个电话:

在onload事件上触发的window.onload

body onload =&#34; barchart()&#34; 这也是触发的。

当你这样做时,你必须考虑任何交互,所以要么得到一个onload或防止任何依赖。

答案 1 :(得分:0)

在脚本中设置window.onload两次,在html中设置一次(在body标签中使用onload属性)。多次设置会覆盖您要先运行的init函数。在页面加载时使用window.addEventListener('load', fn)执行多个函数,或者将要进行的所有函数调用添加到单个init函数中并将其分配给window.onload

答案 2 :(得分:0)

window.onload只接受一个功能。你的第二个功能是覆盖你的第一个。你应该转向更现代的方法:

window.addEventListener('load', function() {
  //first function here
}, false);
window.addEventListener('load', function() {
  //2nd function here
}, false);

答案 3 :(得分:0)

最实用的是只有一个window.onload函数

  1. 从正文标记中删除onload="barChart();"
  2. 从脚本中删除window.onload = init;
  3. 在另一个onload函数
  4. 中的init();之前添加barChart();