我是 JavaScript 的新手,我很难理解如何让 Canvas 与我想做的事情合作。
我试图让 Canvas 外的 HTML 按钮在 Canvas 上创建一个矩形。然后我想让矩形掉下来。我对 Canvas 进行了动画处理,我将按钮设置为在用户输入的坐标处创建一个矩形,但是...... Canvas 不会对其进行动画处理。
它不会像静态创建的矩形那样掉落。我也在为如何让我的按钮每次都创建一个新矩形而不是重新绘制同一个矩形而苦苦挣扎?希望有人能解释的不仅仅是给我代码。 提前致谢。
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
window.onload = addListeners;
function addListeners() {
document.getElementById('b1').addEventListener('click',btn1,false);
function btn1() {
var inputx = document.getElementById("work").value;
var inputy = document.getElementById("y").value;
var inputs = document.getElementById("s").value;
new Rectangle(inputx,inputy,inputs);
// rec.x = inputx;
//rec.y = inputy;
//rec.s = inputs;
}
}
var r2 = new Rectangle(500, 50, 50);
var rec = new Rectangle();
//animate
function animate() {
requestAnimationFrame(animate);
ctx.clearRect(0,0,1450,250);
r2.draw();
r2.update();
rec.draw();
rec.update();
}
矩形代码:
function Rectangle(x,y,s){
this.x = x;
this.y = y;
this.s = s;
this.draw = function(){
//console.log('fuck');
ctx.fillStyle = "rgba(0,200,0,1)";
ctx.fillRect(this.x,this.y,this.s,this.s);
}
this.update = function(){
console.log(this.y);
if((this.y + this.s) <= 250){
this.y= this.y+2;
}
}
最佳答案
由于未调用 animate 方法,该按钮未设置任何动画。同样在你的代码中,当你调用 animate 时,它以无限循环结束,因为 requestAnimationFrame 将继续重复调用 animate,所以我在 requestAnimationFrame(animate) 周围添加了一个条件来检查方 block 高度并在它到达底部时停止运行它,类似于您在更新功能中的内容。
为了在您每次单击按钮时创建一个新的正方形,我将矩形的创建移到了 btn1 函数中。如果您想在创建新方 block 的同时保留旧方 block ,则需要在 Canvas 外跟踪它们,并在每个动画中使用其他所有内容重新绘制它们。
我猜到了你的 html 是什么样子,但你可以运行下面的代码,它会掉落两个方 block ,但请注意,停止条件仅在硬编码的方 block 上。
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
document.getElementById("b1").addEventListener("click", btn1, false);
var r2;
var rec;
function btn1() {
var inputx = document.getElementById("work").value;
var inputy = document.getElementById("y").value;
var inputs = document.getElementById("s").value;
r2 = new Rectangle(500, 50, 50);
rec = new Rectangle(parseInt(inputx, 10), parseInt(inputy, 10), parseInt(inputs, 10));
animate();
}
//animate
function animate() {
if (r2.y + r2.s <= 400) {
requestAnimationFrame(animate);
}
ctx.clearRect(0,0,1450,400);
r2.draw();
r2.update();
rec.draw();
rec.update();
}
function Rectangle(x,y,s){
this.x = x;
this.y = y;
this.s = s;
this.draw = function(){
ctx.fillStyle = "rgba(0,200,0,1)";
ctx.fillRect(this.x,this.y,this.s,this.s);
}
this.update = function(){
this.y= this.y+2;
}
}
<div>
<input id='work'>
<input id='y'>
<input id='s'>
<button id="b1"> Create Sqaure</button>
</div>
<canvas id="myCanvas" width=600 height=400></canvas>
关于javascript - 由 eventlisteners() 创建的 Canvas 上的绘图对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53400296/