绘制矩形
var canvas = document.getElementsByClassName('canvas')[0];
var ctx = canvas.getContext('2d');
ctx.lineWidth = 10;
ctx.moveTo(100,100);
ctx.lineTo(300,100)
ctx.lineTo(300,200)
ctx.lineTo(100,200)
ctx.closePath()
ctx.stroke()
rect()绘制矩形
ctx.rect(100,100,200,100);
ctx.fill()
ctx.stroke()
矩形框
ctx.strokeRect(100,100,200,100);
填充矩形
ctx.fillRect(100,100,200,100)
效果图
demo 模拟重力
<body>
<canvas class="canvas" width="500" height="500" style="width: 500px; height: 500px; border: 1px solid #000;"></canvas>
<script>
var canvas = document.getElementsByClassName('canvas')[0];
console.log(canvas)
var ctx = canvas.getContext('2d');
var boxTop = 10;
var boxLeft = 10;
var boxWidth = 50;
var boxHeight = 50;
var speedX = 1;
var speedY = 1;
var gravity = 1;
var timer = null;
ctx.fillRect(boxLeft, boxTop, boxWidth, boxHeight)
function move() {
var num = 0;
timer = setInterval(() => {
speedY = speedY + gravity
boxTop += speedY;
boxLeft += speedX;
if (boxTop <= 0) {
speedY *= -1;
speedX *= 0.8;
speedY *= 0.8;
}
if (boxTop >= 450) {
speedY *= -1;
speedX *= 0.6;
speedY *= 0.6;
boxTop = 450;
num++;
var time = new Date().getTime()
}
if (boxLeft <= 0) {
speedX *= -1;
speedX *= 0.8;
speedY *= 0.8;
}
if (boxLeft >= 450) {
speedX *= -1;
speedX *= 0.8;
speedY *= 0.8;
boxLeft = 450;
}
if (num > 10 && (new Date().getTime() - time) < 500 ) {
clearInterval(timer)
} else {
ctx.clearRect(0, 0, 500, 500)
ctx.fillRect(boxLeft, boxTop, boxWidth, boxHeight)
}
console.log(speedX + "::::" + speedY + "::::" + boxLeft + "::::" + boxTop)
}, 100);
}
move()
</script>
</body>