
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>Doodle</title>
<style>
#mycanvas {
border: 10px solid #999;
cursor: crosshair;
}
.thumbnail {
border: 2px solid #999;
margin-right: 5px;
}
</style>
</head>
<body>
<p>
<select name="" id="penColor">
<option value="black">黒</option>
<option value="red">赤</option>
<option value="blue">青</option>
<option value="white">白</option>
</select>
<select name="" id="penWidth">
<option value="1">細</option>
<option value="3">中</option>
<option value="5">太</option>
</select>
<input type="button" id="erase" value="消去">
<input type="button" id="save" value="ギャラリーに追加">
</p>
<canvas width="400" height="200" id="mycanvas">
Canvasに対応したブラウザを用意してください。
</canvas>
<div id="gallery"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(function () {
var canvas = document.getElementById('mycanvas');
if (!canvas || !canvas.getContext) return false;
var ctx = canvas.getContext('2d');
var startX,
startY,
x,
y,
borderWidth = 10;
idDrawing = false;
$('#mycanvas').mousedown(function(e) {
isDrawing = true;
startX = e.pageX - $(this).offset().left - borderWidth;
startY = e.pageY - $(this).offset().top - borderWidth;
})
.mousemove(function(e) {
if (!isDrawing) return;
x = e.pageX - $(this).offset().left - borderWidth;
y = e.pageY - $(this).offset().top - borderWidth;
ctx.beginPath();
ctx.moveTo(startX, startY);
ctx.lineTo(x, y);
ctx.stroke();
startX = x;
startY = y;
})
.mouseup(function() {
isDrawing = false;
})
.mouseleave(function() {
isDrawing = false;
});
$('#penColor').change(function() {
ctx.strokeStyle = $(this).val();
});
$('#penWidth').change(function() {
ctx.lineWidth = $(this).val();
});
$('#erase').click(function() {
if (!confirm('本当に消去しますか?')) return;
ctx.clearRect(0, 0, canvas.width, canvas.height);
});
$('#save').click(function() {
var img = $('<img>').attr({
width: 100,
height: 50,
src: canvas.toDataURL()
});
var link = $('<a>').attr({
href: canvas.toDataURL().replace('imge/png','application/octet-stream'),
download: new Date().getTime() + '.png'
});
$('#gallery').append(link.append(img.addClass('thumbnail')));
ctx.clearRect(0, 0, canvas.width, canvas.height);
});
});
</script>
</body>
</html>
【おさかなび-osakanav-】では、この記事の感想!おさかなへの応援メッセージ!おさかなに聞きたい事、質問!記事にしてほしい内容!などを大募集中!
「氏名」「メールアドレス」「内容」の3点をご記入の上「osakana1699@gmail.com」までご応募ください!

