svg生成
createElementNS(),useタグ,clippath,fillの設定の仕方の1例です。
1例
html
<div class="controls">
<button id="applyGradient">グラデーション適用</button>
<button id="applyClipPath">円形クリップパス適用</button>
<button id="reset">リセット</button>
</div>
<svg id="mySvg" width="400" height="300" viewBox="0 0 400 300">
<!-- グラデーションとクリップパスの定義 -->
<defs>
<!-- グラデーション定義 -->
<linearGradient id="gradient" x1="0%" y1="0%" x2="100%" y2="100%">
<stop offset="0%" style="stop-color: #ff6b6b;" />
<stop offset="50%" style="stop-color: #7873f5;" />
<stop offset="100%" style="stop-color: #4ecdc4;" />
</linearGradient>
<!-- 円形のクリップパス -->
<clipPath id="circleClip">
<circle cx="200" cy="150" r="100" />
</clipPath>
</defs>
<!-- 最初は単色の長方形 -->
<rect id="myRect" x="50" y="50" width="300" height="200" fill="#cccccc" rx="10" ry="10" />
</svg>
css
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background-color: #f5f5f5;
font-family: sans-serif;
}
.controls {
position: absolute;
top: 20px;
left: 50%;
transform: translateX(-50%);
display: flex;
gap: 10px;
}
button {
padding: 8px 16px;
cursor: pointer;
background: #7873f5;
color: white;
border: none;
border-radius: 4px;
}
js
// ページ読み込み後に実行
window.onload = function () {
const rect = document.getElementById("myRect");
// グラデーション適用ボタン
document.getElementById("applyGradient").addEventListener("click", function () {
rect.setAttribute("fill", "url(#gradient)");
});
// クリップパス適用ボタン
document.getElementById("applyClipPath").addEventListener("click", function () {
rect.setAttribute("clip-path", "url(#circleClip)");
});
// リセットボタン
document.getElementById("reset").addEventListener("click", function () {
rect.setAttribute("fill", "#cccccc");
rect.removeAttribute("clip-path");
});
};