画布不会在其中显示图像

时间:2016-08-29 20:55:20

标签: javascript html5-canvas

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>

    <canvas id="spriteCanvas" width="500" height="500">
        <img id="coin" width="440" height="40" src="coin.png">
    </canvas>

</body>
</html>

我尝试在canvas元素中放置一个图片,但它不会在浏览器上显示。我知道图片标签有效,因为如果我把它放在画布元素之外就会显示它。此外,如果我检查画布元素,我可以看到图像在里面,但它的尺寸是0乘0.有人可以解释为什么这不起作用?

编辑:我的原始代码通过javascript添加了图片,但它不会在画布上显示。它给了我与上面相同的问题。但我刚刚意识到我失踪了#34; onload&#34;。

原始代码:

var coinImage = new Image();
coinImage.src = "coin.png";
var sCanvas = document.getElementById('spriteCanvas');

function Sprite(canvas, width, height, image){
  this.context = canvas.getContext("2d");
  this.width = width;
  this.height = height;
  this.image = image;
}

Sprite.prototype.render = function() {
  var that = this;
  this.context.drawImage(that.image, 0, 0);
}

function init() {
  var coin = new Sprite(sCanvas, 100, 100, coinImage);
  coin.render();
}

init();

编辑代码:

var coinImage = new Image();
coinImage.src = "coin.png";
var sCanvas = document.getElementById('spriteCanvas');

function Sprite(canvas, width, height, image){
    this.context = canvas.getContext("2d");
    this.width = width;
    this.height = height;
    this.image = image;
}

Sprite.prototype.render = function() {
    var that = this;
    this.context.drawImage(that.image, 0, 0);
}

coinImage.onload = function () {
    var coin = new Sprite(sCanvas, 100, 100, coinImage);
    coin.render();
}

2 个答案:

答案 0 :(得分:1)

这不是<canvas>标记的工作原理。如果您希望图像显示在画布中,则必须使用JavaScript将图像的像素放入画布中。

<canvas>正是他们所说的:画布。它们是您以编程方式绘制的元素。如果您只想在页面上显示图像,则不需要画布,只需要<img>标记即可。实际上,元素不应放在<canvas>

请查看CanvasRenderingContext2D.drawImage()和本教程:HTML5 Canvas Image Tutorial

这个片段:

var canvas = document.getElementById("painting"),
  ctx = canvas.getContext("2d"),
  image = new Image();

image.onload = function() {
  ctx.drawImage(image, 30, 50);
};

image.src = "http://cdn.sstatic.net/Sites/stackoverflow/img/sprites.png?v=10a9e8743fb0";
<canvas id="painting" width="300" height="300"></canvas>

答案 1 :(得分:1)

要在画布上绘制图像,请使用以下方法:

drawImage(image,x,y)

如果你想要绘制的图像不在DOM中,你可以直接从带有几行javascript的URL加载图像。

function loadAndDrawImage(url)
{
    // Create an image object. This is not attached to the DOM and is not part of the page.
    var image = new Image();

    // When the image has loaded, draw it to the canvas
    image.onload = function()
    {
        // draw image...
    }

    // Now set the source of the image that we want to load
    image.src = url;
}
loadAndDrawImage("http://www---.png");