我改编了一个开源游戏,以适应我的奇幻系列小说“Eloik”。
我想用蓝色的圆弧替换一个png图像(大约相同大小)。
我知道我必须画一幅画,但是怎么画呢??
下面是代码的一部分:
// Shield - Boomlight
context.beginPath();
context.strokeStyle = '#0066cc';
context.lineWidth = 10;
context.arc( player.position.x, player.position.y, player.radius,
player.angle + 1.6, player.angle - 1.6, true );
context.stroke();`
我试过下面的代码,但是...png图像没有出现在正确的位置,并且它作为弧线与游戏没有交互……
<html>
<body>
<img id="boom" width="176" height="134" src="http://eloik.com/wp/wp-
content/uploads/2017/05/BOOMLIGHT-jeu-bd.png" alt="">
*In the Javascript :
<script>
window.onload = function() {
var image = new Image();
image.src="http://eloik.com/wp/wp-content/uploads/2017/05/BOOMLIGHT-jeu-
bd.png";
context.beginPath();
context.drawImage(image, 10, 10);
}
</script>
</body>
</html> `
那么现在,出了什么问题呢?
谢谢!:)
发布于 2017-05-16 14:38:57
首先,为了使用drawImage
,我们需要加载它。你可以这样做:
/* core.js: line 57 */
// Create a handle for the image
var shieldImage;
/* core.js: line 133 */
// Create a new image
shieldImage = new Image();
// When it's loaded, execute animate
shieldImage.onload = animate;
// Set the src
shieldImage.src = "http://eloik.com/wp/wp-content/uploads/2017/05/BOOMLIGHT-jeu-bd.png";
这样,只有在加载图像后才会调用animate
函数。然后,为了定位和旋转图像,您可以执行以下操作:
/* core.js: line 420 */
// Set the origin of the canvas on the player position
context.translate(player.position.x, player.position.y);
// Rotate the canvas
context.rotate(player.angle + Math.PI + .2);
// Draw the shield
context.drawImage(shieldImage, -player.radius, -player.radius, player.radius*1.5, player.radius*2.3);
// Rotate the canvas back
context.rotate(-player.angle - Math.PI - .2);
// Reset the initial origin of the canvas
context.translate(-player.position.x, -player.position.y);
因为我们不能旋转图像本身,所以我们使用这个技巧,包括旋转画布、绘制和恢复画布的旋转。我们还平移它,以便在球员的位置上有旋转轴。
您还会注意到我在其中添加了一些数字。这是因为你的盾牌图像不是一个完美的圆圈。我扭曲了它,使它看起来不奇怪与当前的碰撞系统(基于一个圆)。如果你想保持图像的椭圆形,你需要对代码的其余部分进行更多的修改,以使碰撞应用于该形状。
就是这样,你的蓝色弧线被你的PNG图像(Updated JS here)所取代。
附言:你有一个很酷的姓!-和我的一样
https://stackoverflow.com/questions/44002782
复制