我正在尝试在JavaScript画布中显示图像,但是代码无法正常工作。它什么也没显示。我的错误在哪里?
我尝试使用Google的调试器调试代码,但没有任何反应。
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<canvas id="canvas" width="300" height="300"></canvas>
<style>
#canvas {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
</style>
</body>
<script>
const context;
const gameCanvas = document.getElementById("canvas");
context=gameCanvas.getContext("2d");
//context.canvas.height=500;
//context.canvas.width=500;
var imgObj = new Image();
imgObj.src = "dragon.jpg";
var x = 100;
var y = 100;
imgObj.onload = function(){
context.drawImage(imgObj,x,y);
}
</script>
</html>
我想在加载此html文件时看到一个画布以及该画布中的图像。
答案 0 :(得分:0)
您正在尝试重新初始化const
上下文;您应该改用let
。
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<canvas id="canvas" width="300" height="300"></canvas>
<style>
#canvas {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
</style>
</body>
<script>
let context;
const gameCanvas = document.getElementById('canvas');
context = gameCanvas.getContext('2d');
var imgObj = new Image();
imgObj.src = 'dragon.jpg';
var x = 100;
var y = 100;
imgObj.onload = function() {
context.drawImage(imgObj, x, y);
};
</script>
</html>