我将所有图像放在画布上,但随后我添加了一个鼠标跟随事件,其中鼠标光标后面有一个圆圈。一旦我添加了这个新事件,我的所有图像都消失了。我应该怎么做才能将我的图像与新的鼠标跟随事件一起保存在画布上?我尝试在更新功能中添加图像代码,但它仍然不起作用...任何建议和解决方案将不胜感激!
<body>
<canvas id="myCanvas" width="700px" height="600px"></canvas>
<script>
var canvas = document.querySelector("#myCanvas");
var context = canvas.getContext("2d");
var canvasPos = getPosition(canvas);
var mouseX = 700;
var mouseY = 600;
canvas.addEventListener("mousemove", setMousePosition, false);
function setMousePosition(e) {
mouseX = e.clientX - canvasPos.x;
mouseY = e.clientY - canvasPos.y;
}
function update() {
context.clearRect(0, 0, canvas.width, canvas.height);
context.beginPath();
context.arc(mouseX, mouseY, 35, 0, 2 * Math.PI, true);
context.fillStyle = "#eab4e4";
context.fill();
requestAnimationFrame(update);
}
update();
//make mouse position values accurate
function getPosition(el) {
var xPos = 0;
var yPos = 0;
while (el) {
if (el.tagName == "BODY") {
//deal with browser quirks with body/window/document and pg scroll
var xScroll = el.scrollLeft || document.documentElement.scrollLeft;
var yScroll = el.scrollTop || document.documentElement.scrollTop;
xPos += (el.offsetLeft - xScroll + el.clientLeft);
yPos += (el.offsetTop - yScroll + el.clientTop);
} else {
//for all other non-BODY elements
xPos += (el.offsetLeft - el.scrollLeft + el.clientLeft);
yPos += (el.offsetTop - el.scrollTop + el.clientTop);
}
el = el.offsetParent;
}
return {
x: xPos,
y: yPos
};
}
var myImage = new Image();
myImage.src = "MouseEvent/cheese 2.jpg";
myImage.addEventListener("load", loadImage, false);
var myImage2 = new Image();
myImage2.src = "MouseEvent/ballet mouse.jpg";
myImage2.addEventListener("load", loadImage, false);
var myImage3 = new Image();
myImage3.src = "MouseEvent/line.jpg";
myImage3.addEventListener("load", loadImage, false);
function loadImage(e) {
context.drawImage(myImage, 0, 0, 120, 120);
context.drawImage(myImage2, 520, 400, 180, 200);
context.drawImage(myImage3, 150, 200, 500, 220);
}
</script>
</body>