<canvas id="canvas"></canvas>
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth * devicePixelRatio;
canvas.height = window.innerHeight * devicePixelRatio;
canvasW = canvas.width;
canvasH = canvas.height;
//移動させたい要素のx座標を変数化。初期値を設定
let x = 0;
//移動させたい要素を描画する関数
function render() {
ctx.beginPath();
ctx.fillStyle = 'blue';
ctx.fillRect(x, canvasH / 2, 500, 300);
ctx.closePath();
}
//描画を更新する関数
function update() {
//描画を削除
ctx.clearRect(0, 0, canvasW, canvasH);
x++;//x座標を1pxずつ増やす
//x座標が500pxを超えたら。つまり、500px移動したら0に戻る(左端に戻す)
if (x > 500) {
x = 0;
}
//要素を再描画する
render();
//自分(update関数)を描画が終了するたびに呼び出す
window.requestAnimationFrame(update);
}
update();
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.