【问题标题】:drawImage not drawing imagedrawImage 不绘制图像
【发布时间】:2015-08-09 10:38:42
【问题描述】:

我是 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>

提前感谢您的帮助:)

【问题讨论】:

  • 我设法让一些东西在 jsfiddle 中工作,但它几乎立即崩溃。这就像一个螺旋计,是吗?
  • 我正在尝试绘制旋转或旋转的图像,我将在末尾添加 setInterval(rotate, 1000); 代码行 rotate() 函数
  • 添加对 image.onerror 的支持以查看是否存在图像加载错误(例如错误的路径、大写字母、数据...)。
  • 可能是您将图像旋转到画布外部。尝试较小的角度,您可能会看到图像。有关如何使用 JavaScript 正确旋转图像的更多信息,请参阅此处 creativejs.com/2012/01/…

标签: javascript html html5-canvas drawimage


【解决方案1】:

您应该尝试以下几点:

你不应该在 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();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-20
    • 2017-08-14
    • 1970-01-01
    • 1970-01-01
    • 2013-03-08
    • 2012-12-18
    • 2015-11-01
    • 2021-03-02
    相关资源
    最近更新 更多