html5画布未显示完整图像 [英] html5 canvas is not showing full image
本文介绍了html5画布未显示完整图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的图片大小为940 * 300,但是html5画布仅显示了部分镀铬图片。您能帮忙解决此问题吗?
My image size is 940 * 300 but html5 canvas showing only part of image in chrome. Can you please help how to fix this?
下面是代码
<!DOCTYPE html>
<html>
<head>
<style></style>
</head>
<body onload="draw();">
<p>Drag me</p>
<canvas id="paint_area"></canvas>
<script>
function draw() {
var ctx = document.getElementById('paint_area').getContext('2d');
//ctx.fillStyle = '#cc3300';
var img_buffer = document.createElement('img');
img_buffer.src = 'http://www.jobcons.in/homebanner.jpg';
var imgWidth = img_buffer.width;
var imgHeight = img_buffer.height;
ctx.width = imgWidth;
ctx.height = imgHeight;
ctx.drawImage(img_buffer,0,0,imgWidth,imgHeight);
}
</script>
</body>
</html>
推荐答案
两件事:
-
您设置的上下文大小没有太大意义。 画布具有宽度和高度。
您应该真正使用 img_buffer.onload
以确保只在加载图像时才绘制图像,而不是在图像完全加载之前才绘制图像。
You should really use img_buffer.onload
to make sure you only paint the image when it's loaded and not before it's completely loaded.
提琴手: http://jsfiddle.net/pimvdb/TpFQ8/
所以:
<canvas id="paint_area" width="940" height="300"></canvas>
和:
var cv = document.getElementById('paint_area'),
ctx = ctx.getContext('2d');
和:
img_buffer.onload = function() {
var imgWidth = img_buffer.width;
var imgHeight = img_buffer.height;
cv.width = imgWidth;
cv.height = imgHeight;
ctx.drawImage(img_buffer, 0, 0, imgWidth, imgHeight);
}
这篇关于html5画布未显示完整图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文