画布drawimage()不显示图像
Canvas drawimage() not displaying image
我正在尝试在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>
相关文章:
- 从桌面读取python文件时高亮显示代码
- 使用JS如何动态更改显示的html文件中的文本背景颜色
- 如何在生成下载文件时显示加载动画
- React重新渲染但未显示正确的组件
- nodejs-expressjs上传图像并显示它们
- 使用JSP从服务器检索和显示图像
- 音频控件在mouseover上显示,在mouseout上淡出
- 让文本输入幻灯片显示输入时的新文本输入?然后向后滑动
- 使用电话间隙在Android应用程序中显示SQL Lite的数据
- 显示5秒后隐藏潜水
- 画廊图像未显示
- 不显示带有本地json文件数据的谷歌地图脚本
- 如何将json数据显示为html
- 谷歌地图不是以HTML显示,而是在JS Fiddle上工作
- Windows8应用程序(html&Javascript):从图片库(除了文件选择器)显示图像的另一种方式
- 高亮显示时编辑文本大小和颜色
- 有时数据是't显示在浏览器中
- 当鼠标悬停在文本中的单词上时显示警报
- 角度图表;t显示在我的页面中
- 显示图工具提示显示x轴的最后日期值,而不是当前值