画布元素未显示

时间:2019-09-07 18:53:22

标签: html canvas

我在画布上绘制了3个元素,并且在我的页面(https://lodysreizen.nl/route2.html)上运行良好。但是,当我在索引页面(https://lodysreizen.nl/ route2按钮)中实现该页面时,将其加载到div中,仅显示在html代码中绘制的轮廓。 其他两行和点不显示。我在做什么错了?

我更改了代码的顺序(首先是脚本,然后是html,反之亦然)

function draw() {
  var canvas = document.getElementById('japan_canvas');
  if (canvas.getContext) {
    var ctx = canvas.getContext('2d');

    ctx.strokeStyle = "red";
    <!--2 lijnen-->
    ctx.beginPath();
    ctx.moveTo(125, 125); <!--tekst-->
    ctx.lineTo(125, 45);
    ctx.lineTo(45, 125);
    ctx.lineTo(63, 200);
    ctx.lineTo(200, 210);
    <!--ctx.closePath();  dit trekt een lijn vanaf het laatste punt naar het begin punt-->
    ctx.lineWidth = 2; <!--dikte van de lijn-->
    ctx.lineJoin = "round" <!--hoe de lijn er uitziek waar ze een knik maakt.-->
    ctx.stroke();

    <!--de circels-->
    ctx.strokeStyle = "red"; <!--deze kleur werkt nog niet-->
    ctx.beginPath();
    ctx.arc(125, 45, 5, 0, 2 * Math.PI); <!--circel met centrumpunt 125,45)-->
    ctx.fill(); <!--de circel vullen-->

    <!--Path2D-->
  }
}
canvas {
  border: 1px solid black;
}
<body onload="draw();">
  <canvas id="japan_canvas" width="300" height="300"></canvas></body>

1 个答案:

答案 0 :(得分:0)

function createPaint(parent) {
  var canvas = elt('canvas', {});
  var cx = canvas.getContext('2d');


  var toolbar = elt('div', {class: 'toolbar'});
  
  // calls the every function in controls, passing in context,
  // then appending the returned results to the toolbar
  for (var name in controls)
    toolbar.appendChild(controls[name](cx));
  
  var panel = elt('div', {class: 'picturepanel'}, canvas);
  parent.appendChild(elt('div', null, panel, toolbar));
}

/************************************************************************
 * helper functions
 ***********************************************************************/

// creates an element with a name and object (attributes)
// appends all further arguments it gets as child nodes
// string arguments create text nodes
// ex: elt('div', {class: 'foo'}, 'Hello, world!');
function elt(name, attributes) {
  var node = document.createElement(name);
  if (attributes) {
    for (var attr in attributes)
      if (attributes.hasOwnProperty(attr))
        node.setAttribute(attr, attributes[attr]);
  }
  for (var i = 2; i < arguments.length; i++) {
    var child = arguments[i];
    
    // if this argument is a string, create a text node
    if (typeof child == 'string')
      child = document.createTextNode(child);
    node.appendChild(child);
     }
  return node;
}

// figures out canvas relative coordinates for accurate functionality
function relativePos(event, element) {
  var rect = element.getBoundingClientRect();
  return {x: Math.floor(event.clientX - rect.left),
          y: Math.floor(event.clientY - rect.top)};
}

// registers and unregisters listeners for tools
function trackDrag(onMove, onEnd) {
  function end(event) {
    removeEventListener('mousemove', onMove);
    removeEventListener('mouseup', end);
    if (onEnd)
      onEnd(event);
  }
  addEventListener('mousemove', onMove);
  addEventListener('mouseup', end);
}

// loads an image from a URL and replaces the contents of the canvas
function loadImageURL(cx, url)  {
  var image = document.createElement('img');
  image.addEventListener('load', function() {
    var color = cx.fillStyle, size = cx.lineWidth;
    cx.canvas.width = image.width;
    cx.canvas.height = image.height;
    cx.drawImage(image, 0, 0);
    cx.fillStyle = color;
    cx.strokeStyle = color;
    cx.lineWidth = size;
  });
  image.src = url;
}

// used by tools.Spray
// randomly positions dots
function randomPointInRadius(radius) {
  for (;;) {
    var x = Math.random() * 2 - 1;
    var y = Math.random() * 2 - 1;
    // uses the Pythagorean theorem to test if a point is inside a circle
    if (x * x + y * y <= 1)
      return {x: x * radius, y: y * radius};
  }
}

/************************************************************************
 * controls
 ***********************************************************************/

// holds static methods to initialize the various controls;
// Object.create() is used to create a truly empty object
var controls = Object.create(null);

controls.tool = function(cx) {
  var select = elt('select');
  
  // populate the tools
  for (var name in tools)
    select.appendChild(elt('option', null, name));
  
  // calls the particular method associated with the current tool
  cx.canvas.addEventListener('mousedown', function(event) {
    
    // is the left mouse button being pressed?
    if (event.which == 1) {
      
      // the event needs to be passed to the method to determine
      // what the mouse is doing and where it is
      tools[select.value](event, cx);
      // don't select when user is clicking and dragging
      event.preventDefault();
    }
  });
  
  return elt('span', null, 'Tool: ', select);
};

// color module
controls.color = function(cx) {
  var input = elt('input', {type: 'color'});
  
  // on change, set the new color style for fill and stroke
  input.addEventListener('change', function() {
    cx.fillStyle = input.value;
    cx.strokeStyle = input.value;
  });
  return elt('span', null, 'Color: ', input);
};


// save
controls.save = function(cx) {
  // MUST open in a new window because of iframe security stuff
  var link = elt('a', {href: 'currentTab'}, 'Save');
  function update() {
    try {
      link.href = cx.canvas.toDataURL();
    } catch(e) {
      // some browsers choke on big data URLs
      
      // also, if the server response doesn't include a header that tells the browser it
      // can be used on other domains, the script won't be able to look at it;
      // this is in order to prevent private information from leaking to a script;
      // pixel data, data URL or otherwise, cannot be extracted from a "tainted canvas"
      // and a SecurityError is thrown
      if (e instanceof SecurityError)
        link.href = 'javascript:alert(' + 
          JSON.stringify('Can\'t save: ' + e.toString()) + ')';
      else
        window.alert("Nope.");
        throw e;
    }
  }
  link.addEventListener('mouseover', update);
  link.addEventListener('focus', update);
  return link;
};


/************************************************************************
 * tools
 ***********************************************************************/

// drawing tools
var tools = Object.create(null);

// line tool
// onEnd is for the erase function, which uses it to reset
  // the globalCompositeOperation to source-over
tools.Line = function(event, cx, onEnd) {
  cx.lineCap = 'round';
  
  // mouse position relative to the canvas
  var pos = relativePos(event, cx.canvas);
  trackDrag(function(event) {
    cx.beginPath();
    
    // move to current mouse position
    cx.moveTo(pos.x, pos.y);
    
    // update mouse position
    pos = relativePos(event, cx.canvas);
    
    // line to updated mouse position
    cx.lineTo(pos.x, pos.y);
    
    // stroke the line
    cx.stroke();
  }, onEnd);
};

// erase tool
tools.Erase = function(event, cx) {
  
  // globalCompositeOperation determines how drawing operations
  // on a canvas affect what's already there
  // 'destination-out' makes pixels transparent, 'erasing' them
  // NOTE: this has been deprecated
  cx.globalCompositeOperation = 'destination-out';
  tools.Line(event, cx, function() {
    cx.globalCompositeOperation = 'source-over';
  });
};



// initialize the app
var appDiv = document.querySelector('#paint-app');
createPaint(appDiv);
canvas {
  border: 1px solid black;
}
<div id="paint-app"></div>