我是编程的新手,正在尝试为游戏制作“概念验证”项目。我试图从用标题画面制作的图像转到游戏中房间的图像,当用户点击第一个时,但我不完全确定如何去做。我们必须使用canvas作为赋值的一部分,以便将图像放在该元素中。我想我可能会这样,所以我想看到的第一个图像(Obj2)位于我的第二张图像之上,但我注意到了。我的控制台说我的imgObj不明。基本上,我想首先出现imgObj2然后当用户点击它时它会消失以显示imgObj。我很感激任何建议或意见,谢谢!
这是我的代码:
<script>
window.addEventListener("load",eventWindowLoaded, false);
function eventWindowLoaded() {
canvasApp();
}
function canvasSupport() {
return Modernizr.canvas;
}
function canvasApp() {
if (!canvasSupport()) {
return;
}
var theCanvas = document.getElementById("canvasOne");
var context = theCanvas.getContext("2d");
//put code here
var width=1000;
var height=450;
var imageObj = new Image();
var imageObj2 = new Image();
imageObj2.onload=function(){
context.drawImage(imageObj2,0,0);
};
imageObj2.src='clicktostart.jpg';
}
imageObj.onload = function() {
context.drawImage(imageObj, 0, 0);
};
imageObj.src = 'insidemansion.jpg';
</script>
答案 0 :(得分:0)
画布绘图(如标题图片)在画布上绘制后无法更改。
通过清除画布并重新绘制新需要的内容来更改画布内容。
所以你可以像这样完成你的任务
预加载两张图片,以便可以进行绘图
绘制标题图片:context.drawImage(title,0,0);
收听mousedown事件(听取用户在画布上的点击)
单击时,清除画布:context.clearRect(0,0,canvas.width,canvas.height);
绘制房间图像:context.drawImage(room,0,0);
以下是示例代码和演示:
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
var $canvas=$("#canvas");
var canvasOffset=$canvas.offset();
var offsetX=canvasOffset.left;
var offsetY=canvasOffset.top;
var scrollX=$canvas.scrollLeft();
var scrollY=$canvas.scrollTop();
var isDown=false;
var startX;
var startY;
// preload all images
var imgcount=2;
var title=new Image();
title.onload=start;
title.src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house6.jpg";
var room=new Image();
room.onload=start;
room.src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/inside.jpg";
// call start when each image is fully loaded
function start(){
// return if all the images aren't yet loaded
if(--imgcount>0){return;}
// draw the title image
ctx.drawImage(title,0,0);
// listen for mousedown events (clicks)
$("#canvas").mousedown(function(e){handleMouseDown(e);});
}
function handleMouseDown(e){
// tell the browser we're handling this event
e.preventDefault();
e.stopPropagation();
// clear the canvas and draw the room image
ctx.clearRect(0,0,cw,ch);
ctx.drawImage(room,0,0);
}
&#13;
body{ background-color: white; }
#canvas{border:1px solid red;}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<h4>Click the mansion image</h4>
<canvas id="canvas" width=357 height=333></canvas>
&#13;