javascript

SVGアニメーション – javascriptを使う(11) – transform の translate 要素の動的変化

SVGアニメーション – javascriptを使う(11) – transform の translate 要素の動的変化

アニメーションとして取り扱えるSVGのプロパティの transform の translate を試してみます。
下記のサンプルを用意しました。

[js]
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>テストHTML</title>

<style>
#recttest {
stroke: #000;
stroke-width: 2;
}
</style>

</head>
<body>

<svg xmlns="http://www.w3.org/2000/svg"
width = "500"
height = "250"
viewBox = "0 0 500 250"
>
<rect
id = "recttest"
x = "0"
y = "0"
width = "100"
height = "70"
fill = "#999"
/>
</svg>

<script>

let inter_value = 0;
let millisecond = 10;
let dom_rect = document.querySelector("#recttest");

setInterval(() => {

inter_value += 0.2;

dom_rect.setAttribute(‘transform’, ‘translate(‘ + inter_value + ‘, 10)’);

if (inter_value > 50) {
inter_value = 0;
}

}, millisecond)

</script>

</body>
</html>
[/js]

サーバ上のHTMLはこちら(test1.html)

画面にアクセスすると、SVGのrect要素が出力されます。

javascriptによる transform 要素の translate の動的変更で、SVG画像がx軸方向に移動することが確認できます。

SVGアニメーション – javascriptを使う(11) – transform の translate 要素の動的変化(y軸方向の変化)

次の例では、上記のサンプルを、y軸方向へ割り当てて、値を変動させてみました。

ソース全体は以下のようになります。

[js]
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>テストHTML</title>

<style>
#recttest {
stroke: #000;
stroke-width: 2;
}
</style>

</head>
<body>

<svg xmlns="http://www.w3.org/2000/svg"
width = "500"
height = "250"
viewBox = "0 0 500 250"
>
<rect
id = "recttest"
x = "0"
y = "0"
width = "100"
height = "70"
fill = "#999"
/>
</svg>

<script>

let inter_value = 0;
let millisecond = 10;
let dom_rect = document.querySelector("#recttest");

setInterval(() => {

inter_value += 0.2;

dom_rect.setAttribute(‘transform’, ‘translate(10, ‘ + inter_value + ‘)’);

if (inter_value > 50) {
inter_value = 0;
}

}, millisecond)

</script>

</body>
</html>
[/js]

サーバ上のHTMLはこちら(test2.html)

画面にアクセスすると、translate の動的変更で、SVG画像がy軸方向に移動することが確認できます。

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です