Last active
April 17, 2023 03:13
-
-
Save idoushiki/be7f955dbc4d9bca409e501d04c25116 to your computer and use it in GitHub Desktop.
画像を配置するjsコード
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
<html> | |
<head> | |
<meta charset="UTF-8"> | |
</head> | |
<body> | |
<input type="button" class="button"id="btn1" value="消す" onclick="clc();"> | |
<canvas id="c"width="600"height="600"> | |
</canvas> | |
<script> | |
var canvas = document.getElementById('c');//変数canvasにid="c"のキャンバスを読み込む | |
var ctx = canvas.getContext('2d'); | |
ctx.fillStyle = "rgb(255, 255, 255)";//白 | |
ctx.fillRect(0, 0, 600, 600);//canvasの背景を白色にするために白く塗りつぶす | |
function clc(){//canvas内の画像を消す(白で塗りつぶす) | |
ctx.clearRect(0, 0, 600, 600);//canvas内を白く塗りつぶす | |
} | |
canvas.addEventListener('click', onClick, false);//画面がクリックされたらonClickを実行する | |
function onClick(e) { | |
size= 100;//大きさ | |
var img=new Image(); | |
img.src="sample.png";//使う画像(sample.png)を指定する | |
var rect = e.target.getBoundingClientRect(); | |
x = e.clientX- rect.left-size;//x座標(左右)の位置指定 | |
y = e.clientY- rect.top-size;//y座標の(上下)の位置指定 | |
ctx.drawImage(img, x, y,size,size);//canvasに画像を表示する | |
} | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment