Last active
August 28, 2021 13:14
-
-
Save shout-poor/1f1e3b341537b8a70f71c74ddbbad744 to your computer and use it in GitHub Desktop.
HTML上で、画像に罫線を描画するサンプル
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>画像の上に矩形を描画するサンプル</title> | |
<script> | |
const imageUrl = "https://example.com/some/image/url"; | |
const baundaryBox = { x: 0.4, y: 0.4, width: 0.2, height: 0.2 }; | |
function loadImage() { | |
const canvas = document.getElementById("canvas"); | |
const ctx = canvas.getContext('2d'); | |
const img = new Image(); | |
img.src = imageUrl; | |
img.onload = function () { | |
drawImage(canvas, ctx, img); | |
drawBox(canvas, ctx, baundaryBox); | |
} | |
} | |
function drawImage(canvas, ctx, img) { | |
// canvas のサイズを画像に合わせて拡張する | |
canvas.width = img.width; | |
canvas.height = img.height; | |
// 画像描画 | |
ctx.drawImage(img, 0, 0); | |
} | |
function drawBox(canvas, ctx, box) { | |
// 相対座標と画像サイズからピクセル単位の座標を計算 | |
const x = box.x * canvas.width; | |
const y = box.y * canvas.height; | |
const width = box.width * canvas.width; | |
const height = box.height * canvas.height; | |
// 描画 | |
ctx.beginPath(); | |
ctx.strokeStyle = "red"; | |
ctx.rect(x, y, width, height); | |
ctx.lineWidth = 1; | |
ctx.stroke(); | |
} | |
window.onload = loadImage; | |
</script> | |
</head> | |
<body> | |
<div> | |
<canvas id="canvas"></canvas> | |
</div> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment