dha*_*ani 7 html5 canvas html5-canvas
我的图片大小为940*300,但html5画布仅显示chrome中的部分图片.你能帮忙解决这个问题吗?
下面是代码
<!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>
Run Code Online (Sandbox Code Playgroud)
pim*_*vdb 10
两件事情:
您设置的上下文大小没有多大意义.的画布的宽度和高度.
您应该确实只使用img_buffer.onload
它来加载图像,而不是在图像完全加载之前.
小提琴:http://jsfiddle.net/pimvdb/TpFQ8/
所以:
<canvas id="paint_area" width="940" height="300"></canvas>
Run Code Online (Sandbox Code Playgroud)
和:
var cv = document.getElementById('paint_area'),
ctx = ctx.getContext('2d');
Run Code Online (Sandbox Code Playgroud)
和:
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);
}
Run Code Online (Sandbox Code Playgroud)
原因很简单,你不能做
ctx.width= imgWidth;
ctx.height=imgHeight;
Run Code Online (Sandbox Code Playgroud)
你必须这样做
can.width= imgWidth;
can.height=imgHeight;
Run Code Online (Sandbox Code Playgroud)
哪个can
是对画布的引用,而不是画布上下文.
工作范例: