[英]Canvas drawimage() not displaying image
I am trying to make a full screen, responsive image on Canvas. 我正在尝试在Canvas上制作全屏,响应式图像。 I believe I have the sizing figured out, but it isn't drawing the image and is instead leaving the canvas blank.
我相信我已确定尺寸,但是它没有绘制图像,而是将画布留空。
This is the HTML and JavaScript I am currently using: 这是我当前使用的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: CSS:
canvas{
border: 5pt solid black;
position: relative;
height: 100%;
width: 100%;
}
Any help is greatly appreciated. 任何帮助是极大的赞赏。
First off, good job on the minimal example. 首先,在最小的示例上做好工作。 When I ran it in jsFiddle, here's what I got in my javascript console.
当我在jsFiddle中运行它时,这是我在JavaScript控制台中获得的内容。
Uncaught TypeError: Cannot read property 'width' of undefined
Looking at your code, i noticed that it was trying to reference the width and height of the image before it had loaded. 查看您的代码,我注意到它试图在加载图像之前参考图像的宽度和高度。 I put that code inside your
onLoad
function and that error was corrected. 我将该代码放入
onLoad
函数中,该错误已得到纠正。 Next I got this error: 接下来,我收到此错误:
Uncaught TypeError: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': Valid arities are: [3, 5, 9], but 7 arguments provided.
Seeing that, I looked up CanvasRenderingContext2D
on MDN . 看到这一点,我在MDN上查找了
CanvasRenderingContext2D
。 That showed me what it required, and I added a 0,0
for the dx, dy
values. 这向我展示了它的要求,并为
dx, dy
值添加了0,0
。 This is completely wrong of course, but it at least gets the image to render ( jsfiddle link if the below example doesn't work correctly): 这当然是完全错误的,但是至少可以渲染图像(如果下面的示例无法正常工作,请使用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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.