画布drawimage()不显示图像

Canvas drawimage() not displaying image

本文关键字:显示 显示图 图像 drawimage 画布      更新时间:2023-09-26

我正在尝试在Canvas上制作一个全屏、响应灵敏的图像。我相信我已经想好了尺寸,但它并没有画出图像,而是让画布空白。

这是我目前使用的HTML和JavaScript:

<canvas id="MainCanvas"></canvas>
<script> 
    var canvas = document.getElementById("MainCanvas");
    var context = canvas.getContext("2d");
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
    var wRatio = canvas.width / imageObj.width;
    var hRatio = canvas.height / imageObj.height;
    var ratio = Math.min (wRatio, hRatio);
    var imageObj = new Image();  
    imageObj.onload= function() {
     context.drawImage(imageObj, 0, 0, canvas.width, canvas.height,imageObj.width*ratio, imageObj.height*ratio);
    };
    imageObj.src="Local File.jpg";
</script>

CSS:

canvas{
   border: 5pt solid black;
   position: relative;
   height: 100%;
   width: 100%;
}

非常感谢您的帮助。

首先,在最小的示例上做得很好。当我在jsFiddle中运行它时,以下是我在javascript控制台中得到的内容。

Uncaught TypeError: Cannot read property 'width' of undefined

查看您的代码,我注意到它在加载之前试图引用图像的宽度和高度。我把那个代码放在你的onLoad函数里,那个错误就被纠正了。接下来我得到了这个错误:

Uncaught TypeError: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': Valid arities are: [3, 5, 9], but 7 arguments provided.

看到这一点,我在MDN上查找了CanvasRenderingContext2D。这向我展示了它的要求,并为dx, dy值添加了0,0。当然,这是完全错误的,但它至少可以渲染图像(如果下面的例子不能正常工作,则为jsfiddle链接):

var canvas = document.getElementById("MainCanvas");
console.log(canvas);
var context = canvas.getContext("2d");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var imageObj = new Image();  
imageObj.onload= function() {
    var wRatio = canvas.width / imageObj.width;
    var hRatio = canvas.height / imageObj.height;
    var ratio = Math.min (wRatio, hRatio);
    context.drawImage(imageObj, 0, 0, canvas.width, canvas.height,0,0,imageObj.width*ratio, imageObj.height*ratio);
};
imageObj.src="//placehold.it/500";
html, body {
    height: 100%;
}
canvas{
    border: 5pt solid black;
    position: relative;
    height: 100%;
    width: 100%;
    box-sizing: border-box;
    display:block;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/normalize/3.0.3/normalize.css" rel="stylesheet"/>
<canvas id="MainCanvas"></canvas>