【问题标题】:Why I don't get an image drawn on the canvas?为什么我没有在画布上绘制图像?
【发布时间】:2018-10-20 18:14:43
【问题描述】:

没有错误,什么都没有。但是图像仍然没有出现。当我console.log(background); 时,我在控制台中看到图像的 src,就像<img src="ground.png"> 一样。代码如下:

HTML:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Pirate</title>
    <link rel="stylesheet" type="text/css" href="style.css">
  </head>
  <body>
    <canvas id="canvas" width="480" height="240"></canvas>
  <script src="./script.js"></script>
  </body>
</html>

JS:

var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");

var StyleSheet = function(image, width, height) {
  this.image = image;
  this.width = width;
  this.height = height;

  this.draw = function(image, sx, sy, swidth, sheight, x, y, width, height) {
    context.drawImage(image, sx, sy, swidth, sheight, x, y, width, height);
  }
}

var Loader = function(src) {
  this.image = new Image();
  this.image.src = src;
  return this.image;
}

var background = new Loader("ground.png");
console.log(background);
var sprite = new StyleSheet(background, 50, 50);
  sprite.draw(background, 0, 0, 16, 16, 0, 0, 50, 50);

【问题讨论】:

标签: javascript html image canvas


【解决方案1】:

尝试应该在图像加载事件上调用draw,如下所示

var canvas = document.getElementById("canvas");
	var context = canvas.getContext("2d");

	var StyleSheet = function(image, width, height) {
	  this.image = image;
	  this.width = width;
	  this.height = height;

	  this.draw = function(image, sx, sy, swidth, sheight, x, y, width, height) {
		image.onload = function(){
			context.drawImage(image, sx, sy, swidth, sheight, x, y, width, height);
		}
		
	  }
	}

	var Loader = function(src) {
	  this.image = new Image();
	  this.image.src = src;
	  return this.image;
	}

	var background = new Loader("https://pbs.twimg.com/profile_images/902653914465550336/QE3287ZJ_400x400.jpg");
	console.log(background);
	var sprite = new StyleSheet(background, 50, 50);
	  sprite.draw(background, 0, 0, 16, 16, 0, 0, 50, 50);
 &lt;canvas id="canvas" width="480" height="240" style="border:1px solid #000000;"&gt;&lt;/canvas&gt;

Reference

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-18
    • 1970-01-01
    • 1970-01-01
    • 2013-08-25
    相关资源
    最近更新 更多