我正在尝试在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%;
}
非常感谢任何帮助。
答案 0 :(得分:0)
首先,在最小的例子上做得很好。当我在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.
看到这一点,我抬头CanvasRenderingContext2D
on MDN。这向我展示了它的要求,并为0,0
值添加了dx, dy
。当然这是完全错误的,但它至少会使图像呈现(jsfiddle link,如果以下示例无法正常工作):
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";
&#13;
html, body {
height: 100%;
}
canvas{
border: 5pt solid black;
position: relative;
height: 100%;
width: 100%;
box-sizing: border-box;
display:block;
}
&#13;
<link href="https://cdnjs.cloudflare.com/ajax/libs/normalize/3.0.3/normalize.css" rel="stylesheet"/>
<canvas id="MainCanvas"></canvas>
&#13;