【发布时间】:2016-08-22 04:16:39
【问题描述】:
我正在尝试在 javascript 中制作一个 Boomshine 游戏的变体,当我使用 arc 函数绘制圆形时,一切正常。但是,当我尝试用 drawImage 函数替换 arc 函数以使用硬币图像而不是圆形时,当我清除画布以删除先前绘制的圆形时,我开始遇到问题。如果我在渲染图像之前不清除画布,则图像将绘制在画布上,但旧图像仍在画布上。但是当我在再次渲染图像之前清除画布时,画布上没有绘制任何内容。
我已经附上了截图,链接在下面。
这就是我清除画布的方式:
var ctx = game.context;
ctx.fillStyle = "darkgray";
ctx.fillRect(0, 0, game.canvas.width, game.canvas.height);
这就是我绘制图像的方式:
function drawImageBall(x,y,radius,startAngle,color)
{
var img = document.createElement('img');
img.src = 'img/coin-icon.png';
var tmpCtx= game.context;
var ax = x-radius;
var ay = y-radius;
img.onload = function() {
tmpCtx.save();
tmpCtx.beginPath();
tmpCtx.arc(x, y, radius, 0, Math.PI * 2, true);
tmpCtx.closePath();
tmpCtx.clip();
tmpCtx.drawImage(img, ax, ay, img.width, img.height);
tmpCtx.beginPath();
tmpCtx.arc(0, 0, radius, 0, Math.PI * 2, true);
tmpCtx.clip();
tmpCtx.closePath();
tmpCtx.restore();
};
}
Clearing canvas (screenshot) Without clearing canvas (screenshot)
【问题讨论】:
-
我不知道我们是否有足够的资源来弄清楚。我实际上写了一个fiddle 只是作为概念证明;我唯一调整的是模拟弧线绘制的起始角度,因此您发布的代码基本上没有任何问题。为闪烁道歉,我只是想把东西放在那里。
-
您仅在加载图像时绘制图像,而不是每次调用
drawImageBall
标签: javascript canvas