如果在已经具有非整数比例因子的画布上绘制图像,则画布上下文 drawImage() 方法会出现问题。似乎这些图像以一种奇怪的方式被剪裁(有时图像的最右边部分被剪裁,有时最底部被剪裁,有时两者都被剪裁)。这个问题至少出现在 Google Chrome 6(至少稳定)、Chromium 6,甚至可能是最新的(dev-)版本,甚至 Safari 5 中。Firefox 没有这个错误。显然,如果我没记错的话,这是一个 Webkit 问题。让我们看一下下面的代码(提供了完整的演示代码):
<html>
<head>
<style type="text/css">
canvas {
border: solid 1px black;
}
</style>
<script type="text/javascript">
window.onload = function() {
var canvas = document.getElementById("canvas");
var increase = document.getElementById("increase");
var decrease = document.getElementById("decrease");
var scale = document.getElementById("scale");
var context = canvas.getContext("2d");
var image = new Image();
image.src = "image-3x5.png";
var scaleX = 1;
var scaleY = 1;
var repaint = function() {
scale.innerHTML = scaleX + "; " + scaleY;
context.fillStyle = "#FFF";
context.fillRect(0, 0, 1000, 750);
context.drawImage(image, 0, 0, 3, 5);
};
var scaleXF = 1.2; // change both to 2 and it will be fixed
var scaleYF = 1.2;
decrease.onclick = function() {
scaleX /= scaleXF;
scaleY /= scaleYF;
context.scale(1 / scaleXF, 1 / scaleYF);
repaint();
};
increase.onclick = function() {
scaleX *= scaleXF;
scaleY *= scaleYF;
context.scale(scaleXF, scaleYF);
repaint();
};
repaint();
};
</script>
</head>
<body>
<div>
<span id="scale"></span>
</div>
<div>
<canvas id="canvas" width="1000" height="750"></canvas>
</div>
<div>
<input id="decrease" type="button" value="decrease" />
<input id="increase" type="button" value="increase" />
</div>
</body>
</html>
那么它是一个真正的错误吗?或者有什么解决方法吗?
提前致谢。
升级版:
假设我们有以下 BASE64 编码的 3x5 图像:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAMAAAAFCAYAAACAcVaiAAAAEklEQVR42mP4z8DwH4YZyOAAAMufHeNmMS0JAAAAAElFTkSuQmCC