Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/412.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript drawImage不是绘图图像_Javascript_Html_Html5 Canvas_Drawimage - Fatal编程技术网

Javascript drawImage不是绘图图像

Javascript drawImage不是绘图图像,javascript,html,html5-canvas,drawimage,Javascript,Html,Html5 Canvas,Drawimage,我是HTML5新手,请原谅我的无知。 我只是尝试在画布上绘制一个图像,代码运行时没有任何错误,但图像没有绘制 下面是HTML和JS var图像 var帆布; var语境; var画布宽度; var画布高度; window.onload=函数(){ canvas=document.getElementById(“canvas”); context=canvas.getContext(“2d”); 画布宽度=canvas.width; 画布高度=canvas.height; image=docu

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

下面是HTML和JS

var图像
var帆布;
var语境;	
var画布宽度;
var画布高度;
window.onload=函数(){
canvas=document.getElementById(“canvas”);
context=canvas.getContext(“2d”);
画布宽度=canvas.width;
画布高度=canvas.height;
image=document.createElement(“img”);
image.onload=函数(){rotate();};
image.src=“images/roller.png”;
}
函数rotate(){
//清理画布
clearRect(0,0,画布宽度,画布高度);
//将注册点移动到画布的中心
翻译(canvasWidth/2,canvasWidth/2);
//旋转1度
旋转(Math.PI/180);
//将注册点移回画布的左上角
translate(-canvasWidth/2,-canvasWidth/2);
drawImage(image,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();
}

我设法在JSFIDLE中获得了一些工作,但它几乎立即崩溃。它就像一个螺旋描记器,是吗?我试图画一个旋转或旋转的图像,我将添加这个
setInterval(旋转,1000)代码行到末尾
rotate()
function添加对image.onerror的支持,以查看是否存在图像加载错误(例如错误的路径、CAP、数据…)。可能是您将图像旋转到画布外部。尝试一个较小的角度,你可能会看到图像。有关如何使用JavaScript正确旋转图像的更多信息,请参见此处。