我正在尝试在 Canvas 中显示图像。我尝试了多种解决方案,但图像从未显示。简单地通过 HTML 中的标签添加图像效果很好,所以我知道这不是我的文件路径或图像本身的问题...
单独的文件,HTML文件和JS文件
<!DOCTYPE html>
<html>
<head>
<title>DrawingSprite</title>
<script src="MovingSquareGame.js"></script>
</head>
<body>
<div id="gameArea">
<canvas id="myCanvas" width="800" height="480"></canvas>
</body>
</html>
"use strict";
var Game = {
canvas : undefined,
canvasContext : undefined,
balloonSprite : undefined
};
Game.start = function(){
Game.canvas = document.getElementById("myCanvas");
Game.canvasContext = Game.canvas.getContext("2d");
Game.balloonSprite = new Image();
Game.balloonSprite.src = 'sm_balloon.png';
window.setTimeout(Game.mainLoop, 1000);
};
document.addEventListener('DOMContentLoaded', Game.start);
Game.draw = function(){
Game.canvasContext.fillStyle = "yellow";
Game.canvasContext.fillRect(Game.rectanglePosition, 100, 80, 50);
//** I am assuming that this is where the problem is, if I take out this line of code the yellow box outlined above will appear, if this line is in the box will NOT appear**//
~~ Game.drawImage(Game.balloonSprite, {(x : 100, y : 100)}); ~~
};
Game.drawImage = function(sprite, position){
Game.canvasContext.save();
Game.canvasContext.translate(position.x, position.y);
Game.canvasContext.drawImage(sprite, 0, 0, sprite.width, sprite.height,
0, 0, sprite.width, sprite.height);
Game.canvasContext.restore();
};
Game.mainLoop = function(){
Game.draw();
};
A PNG of a balloon should be displayed on the canvas. Thanks again everyone looking forward to getting this one solved :)
最佳答案
首先,
你的代码
Game.drawImage(Game.balloonSprite, {(x : 100, y : 100)});
你的对象中不应该有括号,它应该是:
Game.drawImage(Game.balloonSprite, {x : 100, y : 100));
然后如果我们在之后运行 start 方法
Game.start();
我们结合这些修复,我们得到了一个工作图像绘制到 Canvas : https://jsfiddle.net/0gamu6t2
关于javascript - 使用外部 Javascript 将图像添加到 HTML Canvas ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57704474/