drawImage不是绘制图像

时间:2015-05-27 11:14:32

标签: javascript html5 html5-canvas drawimage

我是HTML5的新手,请原谅我的无知。 我只是想在画布上绘制一个图像,代码运行没有任何错误,但图像没有绘制。

以下是HTML和JS。

var image
var canvas;
var context;	
var canvasWidth;
var canvasHeight;
window.onload = function(){
  canvas=  document.getElementById("canvas");
  context=canvas.getContext("2d");	
  canvasWidth = canvas.width;
  canvasHeight = canvas.height;	
  image = document.createElement("img");
  image.onload = function(){ rotate(); } ;
  image.src = "images/roller.png";
}

function rotate() {
  // Clear the canvas
  context.clearRect(0, 0, canvasWidth, canvasHeight);
	
  // Move registration point to the center of the canvas
  context.translate(canvasWidth/2, canvasWidth/2);
	
  // Rotate 1 degree
  context.rotate(Math.PI / 180);
    
  // Move registration point back to the top left corner of canvas
  context.translate(-canvasWidth/2, -canvasWidth/2);
	
  context.drawImage(image,0,0);
}
<div style="margin: 0 auto; height:400px; width:900px; overflow:hidden;">
<canvas id="canvas" style="margin:0 auto; width:900px; height:auto" align="center"></canvas>
<div style="height:30px; width:50px; position:relative; margin-top:-30%"></div>
</div>

提前感谢您的帮助:)

1 个答案:

答案 0 :(得分:0)

以下是您应该尝试的一些事项:

你不应该在CSS中设置画布大小,它会搞砸一切。而是在JS代码中声明画布的大小:

canvas.width = 900;
canvas.height = 400; //note that you can't set the canvas height to auto.
canvasWidth = canvas.width;
canvasHeight = canvas.height;

2将图像移动到中央,否则它将消失

3重新制作旋转功能以包含画布的save()和restore(),如下所示:

function rotate() {
  // Clear the canvas
  context.clearRect(0, 0, canvasWidth, canvasHeight);

  //Save the canvas
  context.save();

  // Move registration point to the center of the canvas
  context.translate(canvasWidth/2, canvasWidth/2);

  // Rotate 1 degree
  context.rotate(Math.PI / 180);

  //Draw the image so that it appears rotated. Rotation at the center of the image.
  context.drawImage(image,canvasWidth/2-image.width/2, canvasWidth/2-image.height/2);
  // Restore the canvas 
 context.restore();
}