简体   繁体   English

为什么我的HTML5 canvas不能画矩形?

[英]Why can't I draw a rectangle in my HTML5 canvas?

I am trying to draw a red rectangle on my HTML5 canvas. Here is my HTML.我想在我的 HTML5 canvas 上画一个红色矩形。这是我的 HTML。

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset=utf-8>
    <title>My Canvas Experiment</title>
    <link rel="stylesheet" type="text/css" href="main.css" />
    <script src="plotting.js"></script>
    <!--[if IE]>
      <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js">
      </script>
    <![endif]-->
  </head>
  <body>
    <canvas id="plot"></canvas>
  </body>
</html>

Here is plotting.js:这是 plotting.js:

document.onload = function() {
    var c = document.getElementById("plot");
    var ctx = c.getContext("2d");
    ctx.fillStyle("#f00");
    ctx.fillRect(0, 0, 175, 40);
}

Here is main.css:这是 main.css:

body { margin:100px; }

article, aside, figure, footer, header, hgroup, menu, nav, section { 
    display:block;
}
      
#plot {
    width: 500px;
    height: 400px;
}

Why is the page blank?为什么页面是空白的? Chrome Web Developer Console issues no errors. Chrome Web Developer Console 问题没有错误。

Replace: 更换:

ctx.fillStyle("#f00");

with: 与:

ctx.fillStyle="#f00";

Use window.onload instead of document.onload , (keeping @stewe's suggestion). 使用window.onload而不是document.onload (保留@stewe的建议)。

Replace ctx.fillStyle('#f00');替换ctx.fillStyle('#f00'); to ctx.fillStyle = 'red'; to ctx.fillStyle = 'red'; because fillStyle is a variable and NOT the function.因为 fillStyle 是一个变量而不是函数。

I've been having issues all morning with javascript not drawing my shapes.我整个早上都遇到问题 javascript 没有画出我的形状。 Turns out you HAVE to set the width and height on the canvas tag in HTML, and not through the CSS, or the shapes will not draw.原来你必须在 HTML 中的 canvas 标签上设置宽度和高度,而不是通过 CSS,否则形状将不会绘制。

example:例子:

<canvas id="map" width="500" height="500"></canvas>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM