我试图在画布上显示多个箭头,所以当我点击它之后会创建一个全新的箭头。我是初学者,您可以看到,感谢您对如何改进代码的任何帮助或进一步的想法!
var arrowX = -300;
var arrowY = 300;
window.onload = function() {
canvas = document.getElementById("myCanvas");
gc = canvas.getContext("2d");
document.addEventListener("click", mouseClickHandler, false);
window.setInterval(render, 200);
arrow = document.getElementById("arrow");
};
function mouseClickHandler(event) {
if (event.target.tagName.localeCompare("canvas") && event.button == 0) {
arrowX = event.clientX;
arrowY = event.clientY;
}
}
function arrowDown() {
//makes arrow go down
if (arrowY < 450) {
arrowY += 6;
}
if (arrowY < 250) {
arrowY -= 3;
}
}
function render() {
gc.clearRect(0, 0, 1500, 500);
gc.drawImage(arrow, arrowX, arrowY);
arrowDown();
}
<canvas id="myCanvas" width="1500" height="500" style="border:1px solid black;" tabindex="1" onclick="mouseClickHandler(event);">
<img id="arrow" class="arrow" src="https://i.stack.imgur.com/evnjm.png" width="20" height="50" />
</canvas>
答案 0 :(得分:1)
我有一个与此非常相似的问题!继续使用构造函数尝试此代码:
var id = 0;
var arrows = [];
function Arrow(x, y) {
this.id = id++
this.y = y || 0
this.x = x || 0
}
// remove the shape from the array function terminate(id) {
arrows = arrows.filter(arrow => arrow.id !== id)
}
// or add a shape
function spawn() {
arrows.push(new Arrow())
}
function moveAll(){
arrows.forEach(arrow => arrow.y++;)
}
function drawAll(){
arrows.forEach(arrow => /* draw arrow;*/)
}
我希望这有帮助!
这里有类似的question