我是Java脚本和html学习者,我仍然不了解所有内容。我遇到的问题是我的图像没有显示在画布上。 (有一个渐变)。
我看了网上,却找不到任何需要的东西。 这是我正在使用的HTML和Java脚本代码
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var GamePiece;
function startGame() {
"use strict";
var grd = ctx.createLinearGradient(0, 200, 0, 0);
grd.addColorStop(1, "#85E2FF");
grd.addColorStop(0, "blue");
ctx.fillStyle = grd;
ctx.fillRect(0, 0, 1300, 600);
GamePiece = document.createElement("myImg");
GamePiece.setAttribute("width", "175");
GamePiece.setAttribute("height", "175");
GamePiece.onload = function() {
ctx.drawImage(GamePiece, 70, 70);
};
GamePiece.src = "GamePiece.png";
}
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Demo</title>
<link rel="stylesheet" href="Demo.css">
</head>
<body>
<div>
<div class="Header" id="MyHeader">
<a href="MyGame.html">Home</a>
<a class="active" href="Demo.html"> JavaScript Game </a>
<div id="Header-right">
<a href="About"> About </a>
</div>
</div>
</div>
<div class="Title">
<h1> Game Purely Made from JavaScript </h1>
</div>
<center>
<canvas id="myCanvas"></canvas>
<button onClick="startGame()" id="Play">Play Now</button>
</center>
<script src="Demo.js"></script>
</body>
</html>
任何帮助将不胜感激
答案 0 :(得分:0)
问题是您需要绘制一个Image
对象。请参阅drawImage
的文档。
您正在使用createElement
,但向其传递的字符串"myImg"
无效。您应该改为创建Image
对象,并像执行操作一样设置其源和加载事件:
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var GamePiece;
function startGame() {
"use strict";
var grd = ctx.createLinearGradient(0, 200, 0, 0);
grd.addColorStop(1, "#85E2FF");
grd.addColorStop(0, "blue");
ctx.fillStyle = grd;
ctx.fillRect(0, 0, 1300, 600);
GamePiece = new Image(175, 175);
GamePiece.onload = function() {
ctx.drawImage(this, 70, 70);
};
GamePiece.src = "https://via.placeholder.com/175";
}
<center>
<canvas id="myCanvas" width="300" height="300"></canvas>
<button onClick="startGame()" id="Play">Play Now</button>
</center>